标签:nal 方法 方式 单例模式 日志文件 读取 null static 互斥锁
单例模式的使用场景:
懒汉式:有锁才安全,但是效率低
public class Singleton {
private static Singleton instance;
private Singleton (){}
//线程不安全,用public static synchronized Singleton getInstance()
//的方式可以保证线程安全,但是效率低
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
饿汉式:执行效率高,但是初始化就分配内存,浪费内存
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
双检锁/双重校验锁(DCL,即 double-checked locking)
这种方式采用双锁机制,安全且在多线程情况下能保持高性能
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}
静态内部类
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
标签:nal 方法 方式 单例模式 日志文件 读取 null static 互斥锁
原文地址:https://www.cnblogs.com/520beibei/p/9288260.html