public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}mem = allocate(); 1 //Allocate memory for Singleton object.
singleton = mem; 2 //Note that instance is now non-null, but
//has not been initialized.
ctorSingleton(singleton ); 3 //Invoke constructor for Singleton passing
//instance.在 JVM 的即时编译器中存在指令重排序的优化.也就是说上面的第二步和第三步的顺序是不能保证的,最终的执行顺序可能是 1-2-3 也可能是 1-3-2.如果是后者,则在 3 执行完毕、2 未执行之前,被线程二抢占了,这时 instance 已经是非 null 了(但却没有初始化),所以线程二会直接返回 instance,然后使用,然后顺理成章地报错。疑问: 为什么使用了synchronized同步还会被其他线程抢占?
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}mem = allocate(); 1 //Allocate memory for Singleton object.
singleton = mem; 2 //Note that instance is now non-null, but
//has not been initialized.
ctorSingleton(singleton ); 3 //Invoke constructor for Singleton passing
//instance.在 JVM 的即时编译器中存在指令重排序的优化.也就是说上面的第二步和第三步的顺序是不能保证的,最终的执行顺序可能是 1-2-3 也可能是 1-3-2.如果是后者,则在 3 执行完毕、2 未执行之前,被线程二抢占了,这时 instance 已经是非 null 了(但却没有初始化),所以线程二会直接返回 instance,然后使用,然后顺理成章地报错。疑问: 为什么使用了synchronized同步还会被其他线程抢占?
解决方案 »
- hibernate search 对英文进行分词
- rath.msnm.NotificationProcessor:java.net.UnknownHostException: messenger.hotmail.com
- JAVA聊天系统,请问有几种接口可以实现。
- 考考大家Java的开发水平
- STRUTS 如何写 一个验证用户是否登录的类
- 没有自主主键的表间关联关系如何处理
- 新的 Eclipse 创建的 “Dynamic Web Project” 里面没有 web.xml,那 load-on-startup等信息 如何设置??
- 怎样才算是一个合格的J2EE架构师?
- 关于CMP的讨论(言者有分)
- 急!
- 解释下一个啥原理,,这个while里面在循环啥东西
- Java项目已经上线了 有没有什么消息推送的技术???
在同步结束之后的singleton就是为初始化完成的