为了对比几种单例模式在多线程下的实际性能,我编写了一个测试类。
在这个测试类中,我使用了8线程的并发测试。每个线程分别对其进行 重复 1000000 次的获取实例对象操作,最终计算耗时并输出到控制台。
你可以通过注释/取消注释 MyThread 类中的 run 方法来测试不同单例设计模式的性能。
以下性能测试的分析,都来自我本机的测试情况。
测试类
SingletonTester
import java.util.HashSet;/*** 单例模式性能测试类*/public class SingletonTester {public static void main(String[] args) {MyThread thread1 = new MyThread();MyThread thread2 = new MyThread();MyThread thread3 = new MyThread();MyThread thread4 = new MyThread();MyThread thread5 = new MyThread();MyThread thread6 = new MyThread();MyThread thread7 = new MyThread();MyThread thread8 = new MyThread();thread1.setName("thread1");thread2.setName("thread2");thread3.setName("thread3");thread4.setName("thread4");thread5.setName("thread5");thread6.setName("thread6");thread7.setName("thread7");thread8.setName("thread8");thread1.start();thread2.start();thread3.start();thread4.start();thread5.start();thread6.start();thread7.start();thread8.start();}}/*** 线程测试类*/class MyThread extends Thread {@Overridepublic void run() {// 饿汉模式、线程安全// Singleton();// 懒汉模式、线程不安全// Singleton_1();// 懒汉模式 + synchronized同步锁、线程安全Singleton_2();// 懒汉模式 + synchronized同步锁(移到方法体内) 、线程不安全 。( 为了优化 Singleton_2 的性能问题改进的版本1)// Singleton_3();// 懒汉模式 + synchronized同步锁 + double-check 、线程可能不安全(指令重排序)。( 为了解决 Singleton_3 带来的线程不安全问题 )// Singleton_4();// 懒汉模式 + synchronized同步锁 + double-check + volatile 线程安全。( 为了解决 Singleton_4 因为指令重排序可能导致的线程不安全问题 )// Singleton_5();// 懒汉模式 内部类实现// Singleton_6();// 枚举方式// Singleton_7();}/*** Singleton*/public void Singleton() {long time1 = System.currentTimeMillis();HashSet map = new HashSet();for (int i = 0; i < 1000000; i++) {boolean e = map.add(Singleton.getInstance());if (e && i != 0) {System.out.println("Singleton 获取到的对象不相等,非线程安全。");break;}}long time2 = System.currentTimeMillis();System.out.println(this.getName() + "线程 Singleton 测试耗时:" + (time2 - time1) + "ms");}/*** Singleton_1*/public void Singleton_1() {long time1 = System.currentTimeMillis();HashSet map = new HashSet();for (int i = 0; i < 1000000; i++) {boolean e = map.add(Singleton_1.getInstance());if (e && i != 0) {System.out.println("Singleton_1 获取到的对象不相等,非线程安全。");break;}}long time2 = System.currentTimeMillis();System.out.println(this.getName() + "线程 Singleton_1 测试耗时:" + (time2 - time1) + "ms");}/*** Singleton_2*/public void Singleton_2() {long time1 = System.currentTimeMillis();HashSet map = new HashSet();for (int i = 0; i < 1000000; i++) {boolean e = map.add(Singleton_2.getInstance());if (e && i != 0) {System.out.println("Singleton_2 获取到的对象不相等,非线程安全。");break;}}long time2 = System.currentTimeMillis();System.out.println(this.getName() + "线程 Singleton_2 测试耗时:" + (time2 - time1) + "ms");}/*** Singleton_3*/public void Singleton_3() {long time1 = System.currentTimeMillis();HashSet map = new HashSet();for (int i = 0; i < 1000000; i++) {boolean e = map.add(Singleton_3.getInstance());if (e && i != 0) {System.out.println("Singleton_3 获取到的对象不相等,非线程安全。");break;}}long time2 = System.currentTimeMillis();System.out.println(this.getName() + "线程 Singleton_3 测试耗时:" + (time2 - time1) + "ms");}/*** Singleton_4*/public void Singleton_4() {long time1 = System.currentTimeMillis();HashSet map = new HashSet();for (int i = 0; i < 1000000; i++) {boolean e = map.add(Singleton_4.getInstance());if (e && i != 0) {System.out.println("Singleton_4 获取到的对象不相等,非线程安全。");break;}}long time2 = System.currentTimeMillis();System.out.println(this.getName() + "线程 Singleton_4 测试耗时:" + (time2 - time1) + "ms");}/*** Singleton_5*/public void Singleton_5() {long time1 = System.currentTimeMillis();HashSet map = new HashSet();for (int i = 0; i < 1000000; i++) {boolean e = map.add(Singleton_5.getInstance());if (e && i != 0) {System.out.println("Singleton_5 获取到的对象不相等,非线程安全。");break;}}long time2 = System.currentTimeMillis();System.out.println(this.getName() + "线程 Singleton_5 测试耗时:" + (time2 - time1) + "ms");}/*** Singleton_6*/public void Singleton_6() {long time1 = System.currentTimeMillis();HashSet map = new HashSet();for (int i = 0; i < 1000000; i++) {boolean e = map.add(Singleton_6.getInstance());if (e && i != 0) {System.out.println("Singleton_6 获取到的对象不相等,非线程安全。");break;}}long time2 = System.currentTimeMillis();System.out.println(this.getName() + "线程 Singleton_6 测试耗时:" + (time2 - time1) + "ms");}/*** Singleton_7*/public void Singleton_7() {long time1 = System.currentTimeMillis();HashSet map = new HashSet();for (int i = 0; i < 1000000; i++) {boolean e = map.add(Singleton_7.INSTANCE);if (e && i != 0) {System.out.println("Singleton_7 获取到的对象不相等,非线程安全。");break;}}long time2 = System.currentTimeMillis();System.out.println(this.getName() + "线程 Singleton_7 测试耗时:" + (time2 - time1) + "ms");}}/*** 饿汉模式、线程安全* 这种方式实现的单例模式,在类初始化阶段就已经在堆内存中开辟了一块内存,用于存放实例化对象,所以也称为饿汉模式。饿汉模式实现的单例的优点是,可以保证多线程情况下实例的唯一性,而且 getInstance 直接返回唯一实例,性能非常高。* 然而,在类成员变量比较多,或变量比较大的情况下,这种模式可能会在没有使用类对象的情况下,一直占用堆内存。试想下,如果一个第三方开源框架中的类都是基于饿汉模式实现的单例,这将会初始化所有单例类,无疑是灾难性的。*/class Singleton {private static Singleton instance = new Singleton();private Singleton() {}public static Singleton getInstance() {return instance;}}/*** 懒汉模式、线程不安全* 懒汉模式就是为了避免直接加载类对象时提前创建对象的一种单例设计模式。该模式使用懒加载方式,只有当系统使用到类对象时,才会将实例加载到堆内存中*/class Singleton_1 {private static Singleton_1 instance = null;private Singleton_1() {}public static Singleton_1 getInstance() {if (null == instance) {instance = new Singleton_1();}return instance;}}/*** 懒汉模式 + synchronized同步锁、线程安全* 同步锁会增加锁竞争,带来系统性能开销,从而导致系统性能下降,因此这种方式也会降低单例模式的性能。*/class Singleton_2 {private static Singleton_2 instance = null;private Singleton_2() {}public static synchronized Singleton_2 getInstance() {if (null == instance) {instance = new Singleton_2();}return instance;}}/*** 懒汉模式 + synchronized同步锁 、线程不安全* 每次请求获取类对象时,都会通过 getInstance() 方法获取,除了第一次为 null,其它每次请求基本都是不为 null 的。在没有加同步锁之前,是因为 if 判断条件为 null 时,才导致创建了多个实例。基于以上两点,我们可以考虑将同步锁放在 if 条件里面,这样就可以减少同步锁资源竞争。*/class Singleton_3 {private static Singleton_3 instance = null;private Singleton_3() {}public static Singleton_3 getInstance() {if (null == instance) {synchronized (Singleton_3.class) {instance = new Singleton_3();}}return instance;}}/*** 懒汉模式 + synchronized同步锁 + double-check 、线程可能不安全* 这种方式,通常被称为 Double-Check,它可以大大提高支持多线程的懒汉模式的运行性能。但有可能因为 JVM 编译时的重排序而造成线程不安全。*/class Singleton_4 {private static Singleton_4 instance = null;private Singleton_4() {}public static Singleton_4 getInstance() {if (null == instance) {synchronized (Singleton_4.class) {if (null == instance) {instance = new Singleton_4();}}}return instance;}}/*** 懒汉模式 + synchronized同步锁 + double-check + volatile 线程安全*/class Singleton_5 {private volatile static Singleton_5 instance = null;private Singleton_5() {}public static Singleton_5 getInstance() {if (null == instance) {synchronized (Singleton_5.class) {if (null == instance) {instance = new Singleton_5();}}}return instance;}}/*** 懒汉模式 内部类实现*/class Singleton_6 {private static Singleton_5 instance = null;private Singleton_6() {}// 内部类实现public static class InnerSingleton {private static Singleton_6 instance = new Singleton_6();}public static Singleton_6 getInstance() {return InnerSingleton.instance;}}/*** 枚举方式*/enum Singleton_7 {//实例INSTANCE;public static Singleton_7 getInstance() {return INSTANCE;}public void doSomething() {System.out.println("doSomething");}}
在这个测试类中,我使用了8线程的并发测试。每个线程分别对其进行 重复 1000000 次的获取实例对象操作,最终计算耗时并输出到控制台。
你可以通过注释/取消注释 MyThread 类中的 run 方法来测试不同单例设计模式的性能。
以下性能测试的分析,都来自我本机的测试情况。
Singleton
Singleton 类:饿汉模式、线程安全。
饿汉模式实现的单例的优点是,可以保证多线程情况下实例的唯一性,而且 getInstance 直接返回唯一实例,性能非常高。然而,在类成员变量比较多,或变量比较大的情况下,这种模式可能会在没有使用类对象的情况下,一直占用堆内存。试想下,如果一个第三方开源框架中的类都是基于饿汉模式实现的单例,这将会初始化所有单例类,无疑是灾难性的。
class Singleton {private static Singleton instance = new Singleton();private Singleton() {}public static Singleton getInstance() {return instance;}}
Singleton_1
Singleton_1 类:懒汉模式、线程不安全
懒汉模式就是为了避免直接加载类对象时提前创建对象的一种单例设计模式。该模式使用懒加载方式,只有当系统使用到类对象时,才会将实例加载到堆内存中。
但以这种方式实现的懒汉模式,在单线程下运行是没有问题的,但要运行在多线程下,就会出现实例化多个类对象的情况。也就是线程不安全。
class Singleton_1 {private static Singleton_1 instance = null;private Singleton_1() {}public static Singleton_1 getInstance() {if (null == instance) {instance = new Singleton_1();}return instance;}}

虽然是线程不安全的实现方式,但在正常时的性能( 20~36 ms )还是不错的。
Singleton_2
Singleton_2 类:懒汉模式 + synchronized同步锁、线程安全
为了解决 Singleton_1 带来的线程不安全问题,我们需要对 getInstance 方法进行加锁,保证多线程情况下仅创建一个实例。
但同步锁会增加锁竞争,带来系统性能开销,从而导致系统性能下降,因此这种方式也会降低单例模式的性能。
class Singleton_2 {private static Singleton_2 instance = null;private Singleton_2() {}public static synchronized Singleton_2 getInstance() {if (null == instance) {instance = new Singleton_2();}return instance;}}

519~532 ms
虽然是线程安全的,但性能太差了。
Singleton_3
Singleton_3 类: 懒汉模式 + synchronized同步锁 、线程不安全
每次请求获取类对象时,都会通过 getInstance() 方法获取,除了第一次为 null,其它每次请求基本都是不为 null 的。在没有加同步锁之前,是因为 if 判断条件为 null 时,才导致创建了多个实例。基于以上两点,我们可以考虑将同步锁放在 if 条件里面,这样就可以减少同步锁资源竞争。
class Singleton_3 {private static Singleton_3 instance = null;private Singleton_3() {}public static Singleton_3 getInstance() {if (null == instance) {synchronized (Singleton_3.class) {instance = new Singleton_3();}}return instance;}}

虽然是线程不安全的,但可以看到,在没有获取到非单实例的情况下,性能表现已经比 Singleton_2 要好非常多了。( 30 ms 左右 )
Singleton_4
Singleton_4 类:懒汉模式 + synchronized同步锁 + double-check 、线程可能不安全
Singleton_3 虽然有同步锁,但是进入到判断条件里面的线程依然会依次获取到锁创建对象,然后再释放同步锁。所以我们还需要在同步锁里面再加一次判断。这种方式,通常被称为 Double-Check,它可以大大提高支持多线程的懒汉模式的运行性能。
class Singleton_4 {private static Singleton_4 instance = null;private Singleton_4() {}public static Singleton_4 getInstance() {if (null == instance) {synchronized (Singleton_4.class) {if (null == instance) {instance = new Singleton_4();}}}return instance;}}

43~61 ms
可以看到,比之 Singleton_2 (懒汉模式 + synchronized同步锁)的实现方式,性能提升了接近10倍。
Singleton_5
Singleton_5 类:懒汉模式 + synchronized同步锁 + double-check + volatile 线程安全
Singleton_4 之所以说线程可能不安全的原因是:指令重排序。
在 JMM 中,重排序是十分重要的一环,特别是在并发编程中。如果 JVM 可以对它们进行任意排序以提高程序性能,也可能会给并发编程带来一系列的问题。
volatile 在 JDK1.5 之后还有一个作用就是阻止局部重排序的发生,也就是说,volatile 变量的操作指令都不会被重排序。所以使用 volatile 修饰 instance 之后,Double-Check 懒汉单例模式就万无一失了。
class Singleton_5 {private volatile static Singleton_5 instance = null;private Singleton_5() {}public static Singleton_5 getInstance() {if (null == instance) {synchronized (Singleton_5.class) {if (null == instance) {instance = new Singleton_5();}}}return instance;}}
31~54 ms
性能比之 Singleton_4 并没有下降。
Singleton_6
Singleton_6 类:懒汉模式 + 静态内部类 线程安全
Singleton_5 这种同步锁 +Double-Check 的实现方式相对来说,复杂且加了同步锁,使用内部类实现会更简洁一些。
InnerSingleton 是一个静态内部类,当外部类 Singleton_6 被加载的时候,并不会创建 InnerSingleton 实例对象。只有当调用 getInstance() 方法时,InnerSingleton 才会被加载,这个时候才会创建 instance。instance 的唯一性、创建过程的线程安全性,都由 JVM 来保证。所以,这种实现方法既保证了线程安全,又能做到延迟加载。
class Singleton_6 {private static Singleton_6 instance = null;private Singleton_6() {}// 内部类实现public static class InnerSingleton {private static Singleton_6 instance = new Singleton_6();}public static Singleton_6 getInstance() {return InnerSingleton.instance;}}

30~56 ms
Singleton_7
Singleton_7 类:枚举方式实现
最后,我们介绍一种最简单的实现方式,基于枚举类型的单例实现。这种实现方式通过 Java 枚举类型本身的特性,保证了实例创建的线程安全性和实例的唯一性。
enum Singleton_7 {//实例INSTANCE;public static Singleton_7 getInstance() {return INSTANCE;}public void doSomething() {System.out.println("doSomething");}}

24~50 ms
性能与 Singleton ( 饿汉模式 ) 不相上下,
总结
单例的实现方式其实有很多,但总结起来就两种:饿汉模式和懒汉模式,我们可以根据自己的需求来做选择。
如果我们在程序启动后,一定会加载到类,那么用饿汉模式实现的单例简单又实用;如果我们是写一些工具类,则优先考虑使用懒汉模式,因为很多项目可能会引用到 jar 包,但未必会使用到这个工具类,懒汉模式实现的单例可以避免提前被加载到内存中,占用系统资源。

