歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 雙重檢查鎖定和延遲初始化

雙重檢查鎖定和延遲初始化

日期:2017/3/1 9:10:02   编辑:Linux編程

雙重檢查鎖定的由來

在Java程序中,有時需要推遲一些高開銷的對象的初始化操作,並且只有在真正使用到這個對象的時候,才進行初始化,此時,就需要延遲初始化技術。
延遲初始化的正確實現是需要一些技巧的,否則容易出現問題,下面一一介紹。

方案1

public class UnsafeLazyInit{
private static Instance instance;

  public static Instance getInstance(){
    if (instance == null){
         instance = new Instance();
     }
     return instance;
 }
}  

這種做法的錯誤是很明顯的,如果兩個線程分別調用getInstance,由於對共享變量的訪問沒有做同步,很容易出現下面兩種情況:

1.線程A和B都看到instance沒有初始化,於是分別進行了初始化。
2.instance=new Instance操作被重排序,實際執行過程可能是:先分配內存,然後賦值給instance,最後再執行初始化。如果是這樣的話,其他線程可能就會讀取到尚未初始化完成的instance對象。

方案2

public class UnsafeLazyInit{
private static Instance instance;

public static synchronized Instance getInstance(){
    if (instance == null){
         instance = new Instance();
     }
     return instance;
 }
}

這種做法的問題是很明顯的,每一次讀取instance都需要同步,可能會對性能產生較大的影響。

方案3

方案3是一個錯誤的雙重檢測加鎖實現,看代碼:

public class UnsafeLazyInit{
private static Instance instance;

public static Instance getInstance(){
    if (instance == null){
         synchronized(UnsafeLazyInit.classs){
             if (instance == null){
                  instance = new Instance();
               }
          }
     }
     return instance;
  }
}

這種方案看似解決了上面兩種方案都存在的問題,但是也是有問題的。

問題根源

instance = new Instance();
這一條語句在實際執行中,可能會被拆分程三條語句,如下:
memory = allocate();
ctorInstance(memory); //2
instance = memory; //3

根據重排序規則,後兩條語句不存在數據依賴,因此是可以進行重排序的。
重排序之後,就意味著,instance域在被賦值了之後,指向的對象可能尚未初始化完成,而instance域是一個靜態域,可以被其他線程讀取到,那麼其他線程就可以讀取到尚未初始化完成的instance域。


基於volatile的解決方案

要解決這個辦法,只需要禁止語句2和語句3進行重排序即可,因此可以使用volatile來修改instance就能做到了。

private volatile static Instance instance;

因為Volatile語義會禁止編譯器將volatile寫之前的操作重排序到volatile之後。

基於類初始化的解決方案

Java語言規范規定,對於每一個類或者接口C ,都有一個唯一的初始化鎖LC與之對應,從C到LC的映射,由JVM實現。每個線程在讀取一個類的信息時,如果此類尚未初始化,則嘗試獲取LC去初始化,如果獲取失敗則等待其他線程釋放LC。如果能獲取到LC,則要判斷類的初始化狀態,如果是位初始化,則要進行初始化。如果是正在初始化,則要等待其他線程初始化完成,如果是已經初始化,則直接使用此類對象。

public class InstanceFactory{
    private static class InstanceHolder{
        public static Instance = new Instance();
     }
     
    public static Instance getInstance(){
        return InstanceHolder.instance; //這裡將導致instance類被初始化
    }    
}

結論

字段延遲初始化降低了初始化類或者創建實例的開銷,但是增加零訪問被延遲促使化的字段的開銷。在大部分時候,正常的初始化要優於延遲初始化。如果確實需要對實例字段使用線程安全的延遲初始化,請使用上面介紹的基於volatile的延遲初始化方案;如果確實需要對靜態字段使用線程安全的延遲初始化,請使用上面基於類初始化方案的延遲初始化。

Copyright © Linux教程網 All Rights Reserved