饿汉式单例(静态常量初始化)
// 饿汉式单例,线程安全,类加载时初始化实例
public class SingletonHungry {// 使用私有构造函数防止外部实例化private SingletonHungry() {}// 类加载时创建单例对象并赋值给静态final变量,保证线程安全private static final SingletonHungry INSTANCE = new SingletonHungry();// 提供公共的静态方法返回唯一的实例public static SingletonHungry getInstance() {return INSTANCE;}
}
懒汉式单例(线程不安全)
// 懒汉式单例(非线程安全版)
public class SingletonLazyUnsafe {private static SingletonLazyUnsafe instance;private SingletonLazyUnsafe() {}// 第一次调用getInstance方法时创建实例,但这种方法在多线程环境下不安全public static SingletonLazyUnsafe getInstance() {if (instance == null) {instance = new SingletonLazyUnsafe();}return instance;}
}
懒汉式单例(线程安全,同步方法)
// 懒汉式单例(线程安全版,同步方法)
public class SingletonLazySafeSyncMethod {private static SingletonLazySafeSyncMethod instance;private SingletonLazySafeSyncMethod() {}// 使用synchronized关键字同步方法以确保线程安全public static synchronized SingletonLazySafeSyncMethod getInstance() {if (instance == null) {instance = new SingletonLazySafeSyncMethod();}return instance;}
}
懒汉式单例(线程安全,双重检查锁定)
// 懒汉式单例(线程安全版,双重检查锁定DCL - Double Checked Locking)
public class SingletonLazySafeDCL {private volatile static SingletonLazySafeDCL instance; // 使用volatile防止指令重排序private SingletonLazySafeDCL() {}public static SingletonLazySafeDCL getInstance() {if (instance == null) {synchronized (SingletonLazySafeDCL.class) {// 第二次检查,只有在null的情况下才会进入下面的new操作if (instance == null) {instance = new SingletonLazySafeDCL();}}}return instance;}
}
在上述代码中,饿汉式单例在类被加载时就完成了实例化,所以它是线程安全的;而懒汉式单例则是在第一次调用getInstance
方法时才进行实例化,为了解决线程安全问题,懒汉式单例可以通过同步方法或双重检查锁定机制来确保多线程环境下的安全性。其中,双重检查锁定(DCL)是常用的优化手段,它既保证了线程安全,也避免了每次都进行同步操作带来的性能损耗。