懒汉式单例模式很多时候会这么写:
private static Singleton instance;
public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
k但是这样写在多线程的时候就可能会出现问题,JVM为了优化指令会执行指令重排,就后导致 new Singleton() 的时候无序,
详细的看 这个文章 。
解决多线程时可能出现的问题是加 volatile 关键字,
private volatile static Singleton instance;
public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
不过需要在jdk5以后,因为jdk5以前和以后的volatile是不一样的。