单例模式在Java中的7种实现:从懒汉式到静态内部类
·
饿汉式(线程安全)
在类加载时就完成实例化,通过静态变量直接初始化实例。线程安全由JVM类加载机制保证,但可能造成资源浪费(未使用时也加载)。
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
懒汉式(非线程安全)
延迟实例化,首次调用时创建对象。非线程安全,多线程环境下可能创建多个实例。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
同步方法懒汉式(线程安全)
在懒汉式基础上增加synchronized关键字保证线程安全,但每次获取实例都会同步,性能较差。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
双重检查锁定(线程安全)
通过两次判空和synchronized代码块减少同步次数,需使用volatile防止指令重排序。
modelscope.cn/learn/71399
modelscope.cn/learn/71398
modelscope.cn/learn/71395
modelscope.cn/learn/71393
modelscope.cn/learn/71391
modelscope.cn/learn/71389
modelscope.cn/learn/71387
modelscope.cn/learn/71385
modelscope.cn/learn/71383
modelscope.cn/learn/71381
modelscope.cn/learn/71379
modelscope.cn/learn/71377
modelscope.cn/learn/71375
modelscope.cn/learn/71373
modelscope.cn/learn/71371
public class Singleton {
private static volatile Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
静态内部类(线程安全)
利用静态内部类的加载机制实现延迟加载,由JVM保证线程安全且无同步开销。
public class Singleton {
private Singleton() {}
private static class Holder {
static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}
枚举单例(线程安全)
通过枚举类型实现,天然防止反射和序列化破坏单例,写法简洁且线程安全。
public enum Singleton {
INSTANCE;
public void doSomething() {
// 业务方法
}
}
ThreadLocal单例(线程隔离)
每个线程持有独立实例,适用于需要线程隔离的场景,非严格意义上的单例。
public class Singleton {
private static final ThreadLocal<Singleton> threadLocalInstance =
ThreadLocal.withInitial(Singleton::new);
private Singleton() {}
public static Singleton getInstance() {
return threadLocalInstance.get();
}
}
更多推荐

所有评论(0)