标签:懒汉 指令重排序 意思 single 操作 自己的 原子操作 col 可见性
class Single {
private Single() {
System.out.println("ok");
}
private static Single instance = new Single();
public static Single getInstance() {
return instance;
}
}
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static synchronized LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
public class LazySingleton {
private static LazySingleton instance;
private LazySingleton() {}
public static LazySingleton getInstance() {
if (instance == null) {
synchronized(LazySingleton.class) {
if (instance == null) {
instance = new LazySingleton();
}
}
}
return instance;
}
}
但是由于Java编译器允许处理器乱序执行(指令重排序),上述2、3点的顺序是无法保证的。(意思是可能instance != null时有可能还未真正初始化构造器)。
解决方法是通过将instance定义为volatile的。(volatile有两个语义:1. 保证变量的可见性;2. 禁止对该变量的指令重排序)
class Single {
private Single() {}
private static class InstanceHolder {
private static final Single instance = new Single();
}
public static Single getInstance() {
return InstanceHolder.instance();
}
}
标签:懒汉 指令重排序 意思 single 操作 自己的 原子操作 col 可见性
原文地址:http://www.cnblogs.com/wttttt/p/7765076.html