首页 新闻 赞助 找找看

懒汉模式 和 DCL 双检测锁机制的问题

0
悬赏园豆:10 [待解决问题]
public class LazySingleton {  
    private int someField;  
      
    private static LazySingleton instance;  
      
    private LazySingleton() {  
        this.someField = new Random().nextInt(200)+1;         // (1)  
    }  
      
    public static LazySingleton getInstance() {  
        if (instance == null) {                               // (2)  
            synchronized(LazySingleton.class) {               // (3)  
                if (instance == null) {                       // (4)  
                    instance = new LazySingleton();           // (5)  
                }  
            }  
        }  
        return instance;                                      // (6)  
    }  
      
    public int getSomeField() {  
        return this.someField;                                // (7)  
    }  
}  

这是一个懒汉单例模式 + DCL 双检测锁机制。

不加 volatile 关键字,真的存在多线程下,getInstance 拿到的对象不为空但是没有完全初始化的情况吗?

如果存在,能不能写段代码复现一下?

理论我已懂,就是无法再现一个例子推到上面的 DCL 代码。

loveeeeee的主页 loveeeeee | 初学一级 | 园豆:125
提问于:2016-09-20 19:44
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册