通常我使用第一个实现。几天前,我发现了另一个。谁能解释一下这两种实现之间的区别?第二个实现是线程安全的?在第二个例子中使用内部类有什么好处?
//--1st Impl
public class Singleton{
private static Singleton _INSTANCE;
private Singleton() {}
public static Singleton getInstance(){
if(_INSTANCE == null){
synchronized(Singleton.class){
if(_INSTANCE == null){
_INSTANCE = new Singleton();
}
}
}
return _INSTANCE;
}
}
//--2nd Impl
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton _INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder._INSTANCE;
}
}