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;
       }
    }

  • 相关阅读:
    程序员面试金典题解
    Leetcode 解题报告
    常用小算法
    BestCoder 百度之星2016
    jQuery 删除或是清空某个HTML元素。
    dataTable 默认排序设定
    jquery tableExport 插件导出excel (无乱码) 比较简单的表格
    php 根据周数获取当周的开始日期与最后日期
    thinkphp5使用load和use引入第三方类
    判断checkbox是否选中
  • 原文地址:https://www.cnblogs.com/cynchanpin/p/7141234.html
Copyright © 2011-2022 走看看