public class SingletonObject1 {
private static SingletonObject1 instance;
private SingletonObject1(){}
// 方法一,会带来并发问题
// public static SingletonObject1 getInstance(){
// instance = new SingletonObject1();
// return instance;
// }
// 方法二,解决了并发问题,但效率低
// public synchronized static SingletonObject1 getInstance(){
// instance = new SingletonObject1();
// return instance;
// }
// 方法三,看似解决了并发问题,效率也提高了,但存在双double问题
// 未考虑到 new字节码,会导致已分配内存,但构造未完成的情况
// 使用private static SingletonObject1 instance;
public static SingletonObject1 getInstance(){
if (null == instance){
synchronized(SingletonObject1.class){
if (null == instance){
instance = new SingletonObject1();
}
}
}
return instance;
}
}
使用Holder
public class SingletonObject2 {
private SingletonObject2(){};
private static class SingletonObjectHolder{
public final static SingletonObject2 instance = new SingletonObject2();
}
public static SingletonObject2 getInstance() {
return SingletonObjectHolder.instance;
}
}