1. 程式人生 > >單例模式中 的 雙重檢查鎖 概念與用法

單例模式中 的 雙重檢查鎖 概念與用法

它的 lock acc env syn 可見 cost ola check

public class Singleton {
    //私有的 靜態的 本類屬性
    private volatile static Singleton _instance;
    //私有化構造器
    private Singleton() {}
     /*
      * 1st version: creates multiple instance if two thread access
      * this method simultaneouslyX
      */
     public static Singleton getInstance() {
         
if (_instance == null) { _instance = new Singleton(); } return _instance; } /* * 2nd version : this definitely thread-safe and only * creates one instance of Singleton on concurrent environment * but unnecessarily expensive due to cost of synchronization * at every call.
*/ public static synchronized Singleton getInstanceTS() { if (_instance == null) { _instance = new Singleton(); } return _instance; } /* * 3rd version : An implementation of double checked locking of Singleton. * Intention is to minimize cost of synchronization and improve performance, * by only locking critical section of code, the code which creates instance of Singleton class. * By the way this is still broken, if we don‘t make _instance volatile, as another thread can * see a half initialized instance of Singleton.
*/ //雙重檢查鎖:檢查了2次;使用了一個鎖 //此處需要volatile修飾屬性保證它的內存可見性?? public static Singleton getInstanceDC() { if (_instance == null) {//第一次檢查 synchronized (Singleton.class) { if (_instance == null) { //第二次檢查 //線程1創建完對象後,線程會判斷一次就不會創建對象了。解決了首次創建對象的唯一性問題。 _instance = new Singleton(); } } } return _instance; } }

單例模式中 的 雙重檢查鎖 概念與用法