1、某些类创建比较频繁,对于一些大型的对象,这是一笔很大的系统开销。
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
private static synchronized void syncInit() {
if (instance == null) {
instance = new Singleton();
}
}
public static Singleton getInstance() {
if (instance == null) {
syncInit();
}
return instance;
}
2、省去了new操作符,降低了系统内存的使用频率,减轻GC压力。
public class Singleton {
private static Singleton instance = null;
private Singleton() {
}
private static synchronized void syncInit() {
if (instance == null) {
instance = new Singleton();
}
}
public static Singleton getInstance() {
if (instance == null) {
syncInit();
}
return instance;
}
}
JVM内部的机制能够保证当一个类被加载的时候,这个类的加载过程是线程互斥的。这样当我们第一次调用getInstance的时候,JVM能够帮我们保证instance只被创建一次,并且会保证把赋值给instance的内存初始化完毕,