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会大大影响性能,单例的写只有在第一次使用时才会写。
    

      使用读写锁操作,基本上都上的读锁,对其他线程访问没有影响 !


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