我对这种实例化方法有疑问:
从这个网站它说:
class Singleton
{
private static Singleton instance;
private Singleton()
{
System.out.println("Singleton(): Initializing Instance");
}
public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class)
{
if (instance == null)
{
System.out.println("getInstance(): First time getInstance was invoked!");
instance = new Singleton();
}
}
}
return instance;
}
public void doSomething()
{
System.out.println("doSomething(): Singleton does something!");
}
}
然而,从 Elisabeth Freeman、Eric Freeman、Bert Bates、Kathy Sierra、Elisabeth Robson 所著的《Head First Design Pattern》一书中,他们使用相同的方法来实例化 Singleton,唯一的区别是他们将私有静态成员声明为volatile
并且它们 rim关于声明它的要点相当多volatile
。为了在线程之间建立正确的“发生之前的关系”,声明“临界区”同步是不够的吗?