1. 单例模式
-
定义:确保一个类只有一个实例,并提供该实例的全局访问点
- 1、单例类只能有一个实例。
- 2、单例类必须自己创建自己的唯一实例。
- 3、单例类必须给所有其他对象提供这一实例。
-
为什么需要单例模式:避免一个全局使用的类频繁地创建与销毁。
-
优点:
- 1、确保所有的对象都访问一个实例
- 2、由于在系统内存中只存在一个对象,因此可以节约系统资源
- 3、避免对共享资源的多重占用
-
实现:双重校验锁-线程安全
- 为啥双重校验:只使用了一个 if 语句。在 uniqueInstance == null 的情况下,如果两个线程都执行了 if 语句,那么两个线程都会进入 if 语句块内。虽然在 if 语句块内有加锁操作,但是两个线程都会执行 uniqueInstance = new Singleton(); 这条语句,只是先后的问题,那么就会进行两次实例化。因此必须使用双重校验锁,也就是需要使用两个 if 语句:第一个 if 语句用来避免 uniqueInstance 已经被实例化之后的加锁操作,而第二个 if 语句进行了加锁,所以只能有一个线程进入,就不会出现 uniqueInstance == null 时两个线程同时进行实例化操作。
- 为什么用volatile 修饰:
uniqueInstance = new Singleton();
是非原子的,使用 volatile 可以禁止 JVM 的指令重排
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {
}
public static Singleton getUniqueInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}