在之前一篇博客中提到过Java单例模式的实现,Java 单例模式实现方式 ,这次主要分享两个懒汉式线程安全的单例,在面试过程中也会经常被拿来当笔试题,例如写一个线程安全的单例模式。这时候我们肯定想到的是饿汉式,没错,饿汉式是线程安全的,如果你也能写出懒汉式的线程安全的单例是不是更好一些呢。
懒汉式-线程安全
public class Singleton {
private static Singleton singleton = null;
private Singleton(){}
public static synchronized Singleton getInstance(){
if(singleton == null){
singleton = new Singleton();
}
return singleton;
}
}
懒汉式-双重校验锁
public class Singleton {
private static volatile Singleton singleton = null;
private Singleton(){}
public static Singleton getInstance(){
if(singleton == null){
synchronized(Singleton.class){
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
进行两次 if (singleton == null) 的判断是,第一个判断是为了减少synchronized的执行次数。第二个判断是为了防止生成多个实例。