单例模式(Singleton)

  1. //饿汉式单例
    public class HungerSingleton {
     //类加载时直接创建实例
     private static HungerSingleton instance = new HungerSingleton();
     
     private HungerSingleton(){
      
     }
     
     public static HungerSingleton getInstance(){
      return instance;
     }
    }
      
  2. 懒汉式单例
    public class LazySingleton {
      
     private static LazySingleton instance = null;
        private LazySingleton(){
       
        }
        public static LazySingleton getInstance(){
         if (instance == null) {
       instance = new LazySingleton();
         }
         return instance;
        }
    }
    懒汉式单例在单线程下是安全的,但是在多线程下可能会是非安全的
    1.Thread1 if(instance=null)为true且Thread2 if(instance=null)也为true
    这时会创建两个实例,改进方法就是加上(synchronized)同步机制:
    public class LazySingleton {
      
     private static LazySingleton instance = null;
        private LazySingleton(){
       
        }
        public static synchronized LazySingleton getInstance(){
         if (instance == null) {
       instance = new LazySingleton();
         }
         return instance;
        }
    }
    上例中同步机制能防止多线程下的非安全,但是会降低系统的效率,在服务器上为了顾及Singleton、Lazy Initialization与效能问题
      因而有了(双重检索锁定)Double-check Locking的模式,代码如下:
     
    public class LazySingleton{
     private static LazySingleton instance = null;
     private LazySingleton(){
      
     }
     public static LazySingleton getInstance(){
      if(instance==null){
       //只有在第一次建立实例时才会进入同步区,之后由于实例已建立,也就不用进入同步区进行锁定。
       synchronized (LazySingleton.class){
        if (instance==null) {
         instance =new LazySingleton();
        }
       }
      }
      return instance;
     }
    }
    鉴于当前的内存模型的原因,该习语尚未得到广泛使用,就明显成为了一种不安全的编程结构。重定义脆弱的内存模型这一领域的工作正在进行中。尽管如此,即使是在新提议的内存模型中,双重检查锁定也是无效的。对此问题最佳的解决方案是接受同步或者使用一个 static field。
    参考http://www.ibm.com/developerworks/cn/java/j-dcl.html
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值