在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ DCL雙重檢查鎖為什么需要兩層判斷?

DCL雙重檢查鎖為什么需要兩層判斷?

我們知道DCL雙重鎖的寫法是:

if (null == singletonLazy) {
    synchronized (SingletonLazy5.class) {
        if(null == singletonLazy) {
            singletonLazy = new SingletonLazy5();
        }
    }
}

那么為什么有兩層判斷呢?寫成下面這樣有哪些缺點(diǎn)呢?

synchronized (SingletonLazy5.class) {
    if(null == singletonLazy) {
        singletonLazy = new SingletonLazy5();
    }
}
回答
編輯回答
不二心

因?yàn)橐坏﹕ingletonLazy被正確初始化以后,每次訪問null == singletonLazy一定能夠得到false從而不會(huì)重新初始化。但是我們無(wú)需每次都通過上鎖來(lái)判斷null == singletonLazy。所以雙重鎖的目的是為了成功初始化singletonLazy之后不再觸發(fā)加鎖操作。

2017年2月23日 07:10