java双重检验锁模式是什么

发布时间:2022-03-22 17:05:40 作者:iii
来源:亿速云 阅读:138

这篇“java双重检验锁模式是什么”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“java双重检验锁模式是什么”文章吧。 

起因

在对项目进行PMD静态代码检测时,遇到了这样一个问题

Partially created objects can be returned by the Double Checked Locking pattern when used in Java. An optimizing JRE may assign a reference to the baz variable before it calls the constructor of the object the reference points to.

Note: With Java 5, you can make Double checked locking work, if you declare the variable to be volatile.

大概意思是,使用双重检验锁模式,可能会返回一个部分初始化的对象。可能大家有些疑虑,什么是部分初始化的对象,我们下面继续分析 

什么是双重检验锁模式

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

我们看到,在同步代码块的内部和外部都判断了instance == null,这是因为,可能会有多个线程同时进入到同步代码块外的if判断中,如果在同步代码块内部不进行判空的话,可能会初始化多个实例。 

问题所在

这种写法看似完美无缺,但它却是有问题的,或者说它并不担保一定完美无缺。主要原因在于instance = new Singleton();并不是原子性的操作。
创建一个对象可以分为三部:

1.分配对象的内存空间
2.初始化对象
3.设置instance指向刚分配的内存地址
当instance指向分配地址时,instance是不为null的
 

但是,2、3步之间,可能会被重排序,造成创建对象顺序变为1-3-2.试想一个场景:
线程A第一次创建对象Singleton,对象创建顺序为1-3-2;
当给instance分配完内存后,这时来了一个线程B调用了getSingleton()方法
这时候进行instance == null的判断,发现instance并不为null。
但注意这时候instance并没有初始化对象,线程B则会将这个未初始化完成的对象返回。那B线程使用instance时就可能会出现问题,这就是双重检查锁问题所在。 

使用volatile

对于上述的问题,我们可以通过把instance声明为volatile型来解决

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

但是必须在JDK5版本以上使用。 

静态内部类

public class Singleton {  
    private static class SingletonHolder {  
        private static final Singleton INSTANCE = new Singleton();  
    }  
    private Singleton (){}  
    public static final Singleton getInstance() {  
        return SingletonHolder.INSTANCE; 
    }  
}

这种写法是目前比较推荐的一种写法,采用静态内部类的方式,既实现了懒加载又不会出现线程安全问题。而且减少了synchronized的开销。

以上就是关于“java双重检验锁模式是什么”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。

推荐阅读:
  1. 双重检查锁为什么要使用volatile字段?
  2. 双重检查锁单例模式为什么要用volatile关键字?

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:webpack2缓存优化的方法

下一篇:Java有锁并发、无锁并发和CAS实例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》