Singleton多种实现方式的在多线程情况下的优缺点
一、饿汉式
缺点:不能懒加载
// 不能懒加载
public class SingletonObject1 {
private static final SingletonObject1 instance = new SingletonObject1();
private SingletonObject1(){
}
public static SingletonObject1 getInstance(){
return instance;
}
}
二、懒汉式(线程不安全)
public class SingletonObject2 {
private static SingletonObject2 instance = null;
private SingletonObject2(){
}
public static SingletonObject2 getInstance(){
// 线程不安全模式
if (instance == null)
instance = new SingletonObject2();
return SingletonObject2.instance;
}
}
三、懒汉式(线程安全,效率低)
public class SingletonObject3 {
private static SingletonObject3 instance = null;
private SingletonObject3(){
}
// 串行执行,效率低下
public static synchronized SingletonObject3 getInstance(){
if (instance == null)
instance = new SingletonObject3();
return SingletonObject3.instance;
}
}
四、懒汉式(线程安全,效率高,但是有空指针异常)
public class SingletonObject4 {
private static SingletonObject4 instance = null;
private SingletonObject4(){
}
// 双重检查机制,严格单例,解决了懒加载的问题,但是也带来了问题:空指针异常
public static SingletonObject4 getInstance(){
if (instance == null){
synchronized (SingletonObject4.class){
if (instance == null)
instance = new SingletonObject4();
}
}
return SingletonObject4.instance;
}
}
五、懒汉式(解决四的问题,禁止指令重排序,加volatile关键字)
public class SingletonObject5 {
private static volatile SingletonObject5 instance = null;
private SingletonObject5(){
}
// 双重检查机制,严格单例,解决了懒加载的问题,但是也带来了问题:空指针异常
public static SingletonObject5 getInstance(){
if (instance == null){
synchronized (SingletonObject5.class){
if (instance == null)
instance = new SingletonObject5();
}
}
return SingletonObject5.instance;
}
}
六、内部静态类的更加优雅的方式
public class SingletonObject6 {
private SingletonObject6(){
}
private static class InstanceHolder{
private final static SingletonObject6 instance = new SingletonObject6();
}
public static SingletonObject6 getInstance(){
return InstanceHolder.instance;
}
}