java單例模式-懶加載

    單例模式-我們經常都在使用,以下是懶加載的兩種實現方式,僅當學習!

    方案一:synchronized

private static SingletonLazy instance = null;
private SingletonLazy(){};
public static  SingletonLazy getInstance(){
   if (null == instance){
       createInstance();
   }
   return instance;
}

private synchronized static SingletonLazy createInstance(){
   if (null == instance){
       instance = new SingletonLazy();
   }
   return instance;
}


  方案二:lock (推薦使用

private static SingletonLazyLock instance = null;
private SingletonLazyLock(){};

//加讀寫鎖
private static ReadWriteLock rwl = new ReentrantReadWriteLock();

/**
 * 單例模式 懶加載併發
 * @return
 */
public static SingletonLazyLock getInstance(){
    rwl.readLock().lock();
    try {
        if (null == instance){
            rwl.readLock().unlock();
            rwl.writeLock().lock();
            if(null == instance){
                instance = new SingletonLazyLock();
            }
            rwl.writeLock().unlock();

        }
        rwl.readLock().lock();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        rwl.readLock().unlock();
    }

    return instance;
}

      單例雖然沒有緩存寫的那麼平凡,如果在getinstance方法上加sychonize會大大影響性能,單例的寫只有在第一次使用時纔會寫。
    

      使用讀寫鎖操作,基本上都上的讀鎖,對其他線程訪問沒有影響 !


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章