我是靠谱客的博主 柔弱百褶裙,这篇文章主要介绍java的双重检查锁问题,现在分享给大家,希望可以做个参考。

通过双重检查锁(double-checked locking)(在并发场景下实现延迟初始化的优化 问题隐患(可参考 The "Double-Checked Locking is Broken" Declaration),推荐解决方案中较为 简单一种(适用于 JDK5 及以上版本,将目标属性声明为 volatile 型(比如修改 helper 的属 性声明为`private volatile Helper helper = null;`)。

正例:

public class Singleton {
   private static Singleton instance = null;
   private Singleton() {}
 
   public static Singleton getInstance() {
   if (instance == null){
     synchronized(Singleton.class){
       if (instance == null)
         instance = new Singleton();
     }
   }
   return instance;
   }
}

反例:
public class LazyInitDemo {
private Helper helper = null ;
public Helper getHelper () {
if ( helper == null ) {
synchronized ( this ) {
if ( helper == null ) { helper = new Helper (); }
}
}
return helper ;
}
// other methods and fields...
}
 

最后

以上就是柔弱百褶裙最近收集整理的关于java的双重检查锁问题的全部内容,更多相关java内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(91)

评论列表共有 0 条评论

立即
投稿
返回
顶部