public class Singleton {
private static class SingletonHolder{
final static Singleton instance= new Singleton ();
}
private Singleton(){};
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
JVM加载类不会产生线程安全问题,即两个线程同时去加载这个类,也会按顺序加载,因此会保存SingletonHolder实例的唯一性
在加载singleton时并不加载它的内部类SingletonHolder,而在调用getInstance()时调用SingletonHolder时才加载SingletonHolder,从而调用singleton的构造函数,实力化singleton,从而达到lazy loading的效果。
private static class SingletonHolder{
final static Singleton instance= new Singleton ();
}
private Singleton(){};
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
JVM加载类不会产生线程安全问题,即两个线程同时去加载这个类,也会按顺序加载,因此会保存SingletonHolder实例的唯一性
在加载singleton时并不加载它的内部类SingletonHolder,而在调用getInstance()时调用SingletonHolder时才加载SingletonHolder,从而调用singleton的构造函数,实力化singleton,从而达到lazy loading的效果。