Java 双重验证懒汉模式
一、synchronized 实现双重验证懒汉模式
注: volatile 防止出现指令重排序
/**
* 测试单例
*/
public class TestSingleton {
public static void main(String[] args) {
Singleton singleton1 = Singleton.getInstance();
Singleton singleton2 = Singleton.getInstance();
System.out.println(singleton1 == singleton2);
}
}
/**
* 单利懒汉模式,采用双重校验
*/
class Singleton {
private Singleton() {
}
private static volatile Singleton singleton = null;
public static Singleton getInstance() {
// 只有为null时候才创建
if (singleton == null) {
synchronized (Singleton.class) { // 保证执行的线程安全,不会产生多个对象
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
二、ReentrantLock 非公平锁实现双重验证懒汉模式
/**
* 名称:单例懒汉模式
*
* 介绍:lock 重入锁,实现双重验证懒汉模式,并加以volatile修饰,防止出现低概率指令重排序
*/
public class LockStudy {
Logger log = Logger.getLogger(this.getClass().getName());
final static Lock lock = new ReentrantLock(false); // 定义非公平锁
private LockStudy () {
}
private static volatile LockStudy lockStudy = null;
public static LockStudy getInstance() {
if (lockStudy == null) {
lock.lock();
try {
if (lockStudy == null) {
lockStudy = new LockStudy();
}
} finally {
lock.unlock();
}
}
return lockStudy;
}
public static void main(String[] args) {
LockStudy lockStudy1 = LockStudy.getInstance();
LockStudy lockStudy2 = LockStudy.getInstance();
System.out.println(lockStudy1 == lockStudy2);
}
}