首页 > 编程语言 > 详细

java单例模式-懒加载

时间:2016-04-17 23:16:59      阅读:449      评论:0      收藏:0      [点我收藏+]

    单例模式-我们经常都在使用,以下是懒加载的两种实现方式,仅当学习!

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

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


本文出自 “吸博取精自我更新” 博客,请务必保留此出处http://wyong.blog.51cto.com/1115465/1764864

java单例模式-懒加载

原文:http://wyong.blog.51cto.com/1115465/1764864

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!