单例模式的 3 种实现方式

1. 在单例类被加载的时候实例化,这种实现方式被称为饿汉模式。

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

2. 在第一次用到单例对象时实例化,这种实现方式被称为懒汉模式。

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

      需要注意的是这种实现方式是线程不安全的。假设在单例类被实例化之前,有两个线程同时在获取单例对象,线程1在执行完第8行 if (instance == null) 后,线程调度机制将 CPU 资源分配给线程2,此时线程2在执行第8行  if (instance == null) 时也发现单例类还没有被实例化,这样就会导致单例类被实例化两次。为了防止这种情况发生,需要对 getInstance() 方法同步。下面看改进后的懒汉模式:

 1 public class Singleton {
 2     private static Singleton instance;
 3     
 4     private Singleton() {
 5     }
 6     
 7     // 线程安全的懒汉模式
 8     public synchronized static Singleton getInstance() {
 9         if (instance == null) {
10             instance = new Singleton();
11         }
12         
13         return instance;
14     }
15 }

3. 双重加锁(double check)

      第2种实现方式中,每次获取单例对象时都会加锁,这样就会带来性能损失。双重加锁实现本质也是一种懒汉模式,相比第2种实现方式将会有较大的性能提升。

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

       就算在单例类被实例化时有多个线程同时通过了第8行代码 if (instance == null) 的判断,但同一时间只有一个线程获得锁后进入同步区。由于通过第8行判断的每个线程依次都会获得锁进入同步区,所以进入同步区后还要再判断一次单例类是否已被其它线程实例化,以避免多次实例化。由于双重加锁实现仅在实例化单例类时需要加锁,所以相较于第2种实现方式会带来性能上的提升。另外需要注意的是双重加锁要对 instance 域加上 volatile 修饰符。由于 synchronized 并不是对 instance 实例进行加锁(因为现在还并没有实例),所以线程在执行完第11行修改 instance 的值后,应该将修改后的 instance 立即写入主存(main memory),而不是暂时存在寄存器或者高速缓冲区(caches)中,以保证新的值对其它线程可见。

      补充:第9行可以锁住任何一个对象,要进入同步区必须获得这个对象的锁。由于并不知道其它对象的锁的用途,所以这里最好的方式是对 Singleton.class 进行加锁。

猜你喜欢

转载自www.cnblogs.com/qifenghao/p/8986538.html