饿汉式:线程安全
public class Singleton{
private Singleton(){}
private static final Singleton s = new Singleton();
public static get instance(){
return s;
}
}
懒汉式:通过加锁的方式保证了线程安全,但是也因此影响了性能
public class Singleton{
private Singleton(){}
private static Singleton s;
public synchronized static get instance(){
if(s == null){
s = new Singleton();
}
return s;
}
}
双重检锁:线程安全
public class Singleton{
private Singleton(){}
// volatile 禁止指令重排,干扰程序运行顺序
private static volatile Singleton s;
public static get instance(){
if(s == null){
synchronized(Singleton.class){
if(s == null) { // 加一重判断,防止多线程环境中多次实例化
s = new Singleton();
}
}
}
return s;
}
}
内部类:线程不安全,可以通过反射破坏单例
public class Singleton{
private Singleton(){}
private static class Inner{
public static final Singleton INSTANCE = new Singleton();
}
public static get instance(){
return Inner.INSTANCE;
}
}
枚举:枚举天生就是线程安全的,没有构造方法,因此不能使用反射去破坏单例
public enum Singleton{
INSTANCE;
public static get instance(){
return INSTANCE;
}
}