public class Singleton
{
private volatile static Singleton singleton = null;
private Singleton()
{
}
public static Singleton getInstance()
{
if (singleton == null)
{
synchronized (Singleton.class) {
if (singleton == null)
{
singleton = new Singleton();
}
}
}
return singleton;
}
}
或者
使用JVM
本身机制保证了线程安全问题;由于SingletonHolder
是私有的,除了getInstance()
之外没有办法访问它,因此它只有在getInstance()
被调用时才会真正创建;同时读取实例的时候不会进行同步,没有性能缺陷。
public class Singleton
{
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton()
{
}
public static final Singleton getInstance()
{
return SingletonHolder.INSTANCE;
}
}