zoukankan      html  css  js  c++  java
  • Java并发:线程安全的单例模式

    转载请注明出处:jiq•钦'stechnical Blog

    1、饿汉式

    public class Singleton {
      private final static Singleton INSTANCE = new Singleton();
      private Singleton() { }
      public static Singleton getInstance() {
         return INSTANCE;
       }
    } 
    缺点:类载入时即分配空间。若不使用则较为占用内存空间。


    2、懒汉式

    2.1普通加锁模式

    public class Singleton {
      private static Singleton instance = null;
      private Singleton() { }
     
      public static synchronized Singleton getInstance() {
         if(instance == null) {
            instance = new Singleton();
         }
         return instance;
       }
    } 
    缺点:每一个线程调用getInstance都要加锁,效率低,我们想要仅仅在第一次调用getInstance时加锁。请看以下的双重检測方案


    2.2占位符模式(推荐)

    属于懒汉式单例,由于Java机制规定。内部类SingletonHolder仅仅有在getInstance()方法第一次调用的时候才会被载入(实现了lazy),并且其载入过程是线程安全的。内部类载入的时候实例化一次instance。

    public class Singleton {
      private Singleton() { }
       privatestatic class SingletonHolder {  
    //内部类。第一次使用时才载入,且仅仅能SingletonHolder类能訪问
    //特别注意:static域中改动共享变量是线程安全的,由JVM保障
         static Singleton INSTANCE = new Singleton();
       }
      public static Singleton getInstance() {
         return SingletonHolder.INSTANCE;
       }
    }


    2.3双重检測

    普通双重检測:

    public class Singleton {
      private static Singleton instance = null;
      private Singleton() { }
      public static Singleton getInstance() {
         if(instance == null) {
            synchronzied(Singleton.class) {
               if(instance == null) {
                   instance = new Singleton();
               }
            }
         }
         return instance;
       }
    }
    缺点:指令重排问题,參考我的这篇文章

    解决方式:

    针对instance实例变量用volatile修饰就能够了,volatile修饰的话就能够确保instance = new Singleton();相应的指令不会重排序:

    public class Singleton {
      private static volatile Singletoninstance = null;  //以volatilekeyword修饰防止指令重排
      private Singleton() { }  //构造函数为私有,防止被实例化
      public static Singleton getInstance() {
         if(instance == null) {     //双重检測
            synchronzied(Singleton.class) {
               if(instance == null) {
                   instance = new Singleton();
               }
            }
         }
         return instance;
       }
    }

  • 相关阅读:
    【转】Quartz企业作业调度配置参考
    [转]quartz中参数misfireThreshold的详解
    【转】MFC下拉框使用方法
    MFC中使用tinyxml
    【转】MYSQL中复制表结构的几种方法
    C++错误:重定义 不同的存储类
    【转】vbsedit提示“无法创建空文档”解决办法
    wordbreak和wordwrap
    css字体font
    js和jquery书籍
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/7141234.html
Copyright © 2011-2022 走看看