zoukankan      html  css  js  c++  java
  • 单例模式

    用于创建单一类。例如一些工具类等。

    主要有以下四种实现:

    lazy load,线程不安全

     1 public class UnsafeLazySingleton {
     2 
     3     private static UnsafeLazySingleton instance;
     4 
     5     private UnsafeLazySingleton() {
     6     }
     7 
     8     public static UnsafeLazySingleton getInstance() {
     9         if (instance == null) {
    10             instance = new UnsafeLazySingleton();
    11         }
    12         return instance;
    13     }
    14 }

    lazy load,线程安全,但是每次获取需要锁,效率较差

     1 public class SafeLazySingletonWithLock {
     2 
     3     private static SafeLazySingletonWithLock instance;
     4 
     5     private SafeLazySingletonWithLock() {
     6     }
     7 
     8     public static synchronized SafeLazySingletonWithLock getInstance() {
     9         if (instance == null) {
    10             instance = new SafeLazySingletonWithLock();
    11         }
    12         return instance;
    13     }
    14 }

    线程安全

     1 public class UnLazySingleton {
     2 
     3     private static UnLazySingleton instance = new UnLazySingleton();
     4 
     5     private UnLazySingleton() {
     6     }
     7 
     8     public static UnLazySingleton getInstance() {
     9         return instance;
    10     }
    11 }

    双检索

     1 public class DoubleCheckedSingleton {
     2 
     3     private volatile static DoubleCheckedSingleton singleton;
     4 
     5     private DoubleCheckedSingleton() {
     6     }
     7 
     8     public static DoubleCheckedSingleton getSingleton() {
     9         if (singleton == null) {
    10             synchronized (DoubleCheckedSingleton.class) {
    11                 if (singleton == null) {
    12                     singleton = new DoubleCheckedSingleton();
    13                 }
    14             }
    15         }
    16         return singleton;
    17     }
    18 }

    推荐最后一种方式,即实现了lazy load,又是线程安全,并且只有在初次加载并发的时候需要锁,其他时候不会用到锁,效率也有保障。PS:首次并发的时候出现冲突,都运行到代码10,当一个线程成功初始化后,由于单例是volatile修饰的,其他线程可见,代码11判断后不会发生重复定义,保证线程安全。

  • 相关阅读:
    再谈H2的MVStore与MVMap
    log4j动态日志级别调整
    wireshark抓文件上传的包的结果记录
    struts2对properties资源的处理
    Spring core resourc层结构体系及JDK与Spring对classpath中资源的获取方式及结果对比
    [工具使用] visualvm 通过jmx不能连接
    oracle 安装 启动listener 建库相关
    vscode
    XSSFWorkbook
    TearmQuery()
  • 原文地址:https://www.cnblogs.com/avalon-merlin/p/10522378.html
Copyright © 2011-2022 走看看