为什么要用双重校验锁实现单例模式?
单例实现有饿汉模式与懒汉模式,懒汉模式能够延迟加载,使用较多,但是懒汉模式在多线程下会出现问题,即有可能会产生多个实例。
饿汉模式
public class HungrySingleton {
/**
* 定义一个变量存储实例,在饿汉模式中直接实例化
*/
private static HungrySingleton uniqueInstance = new HungrySingleton();
/**
* 私有化构造方法
*/
private HungrySingleton(){
}
/**
* 提供一个方法为客户端提供实例
*/
public static HungrySingleton getUniqueInstance(){
return uniqueInstance;
}
}
饿汉模式在类加载的时候就完成了实例化,避免了多线程的同步问题。
缺点是:因为类加载时就实例化了,没有达到Lazy Loading (懒加载) 的效果,如果该实例没被使用,内存就浪费了。
懒汉模式
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {
}
//懒汉式 -- 其特点是延迟加载,即当需要用到此单一实例的时候,才去初始化此单一实例
public static Singleton getUniqueInstance(){
if (uniqueInstance == null){
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
懒汉模式只有在方法第一次被访问时才会实例化,达到了懒加载的效果。
但是这种写法有个致命的问题,就是多线程的安全问题。假设对象还没被实例化,然后有两个线程同时访问,那么就可能出现多次实例化的结果,所以这种写法不可采用。
双重校验锁
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {
}
public static Singleton getUniqueInstance() {
//先判断对象是否已经实例过,没有实例化过才进⼊加锁代码
if (uniqueInstance == null