說一說你對DCL雙檢查鎖的瞭解?

    DCL雙檢查鎖是的初衷是爲了解決實現單例對象的懶加載時,避免過分同步致使的性能開銷,在獲取單例的構造方法中經過兩層if null的空校驗進行雙層檢查,在最裏面的一層校驗外加了synchronized同步,可是問題就是出在當構造單例實例對象時,會出現指令重排序,即實例的寫入操做和實例字段的寫入操做存在重排序。在外層的if null校驗實例時獲得不爲空即對實例進行了訪問。可是此時會存在訪問部分構造的實例對象的問題。能夠經過volatile限制對實例的指令重排序解決,可是此種方法會有必定的性能開銷。另外一種方法是經過靜態內部類的變量延遲加載的機制實現。java

 

參考資料:性能

Java內存模型FAQ(十一)新的內存模型是否修復了雙重鎖檢查問題?this

// double-checked-locking - don't do this!

private static Something instance = null;

public Something getInstance() {
  if (instance == null) {
    synchronized (this) {
      if (instance == null)
        instance = new Something();
    }
  }
  return instance;
}
private static class LazySomethingHolder {
  public static Something something = new Something();
}

public static Something getInstance() {
  return LazySomethingHolder.something;
}
相關文章
相關標籤/搜索