【发布时间】:2011-05-27 19:42:06
【问题描述】:
我正在阅读这个Best Singleton Implementation In Java,但它不是线程安全的。
根据维基:
if(singleton==null) { synchronized(Singleton.class) { // this is needed if two threads are waiting at the monitor at the // time when singleton was getting instantiated if(singleton==null) singleton= new Singleton(); }
}
但是 Find Bugs 实用程序在这方面给出了两个错误: 1.双重空检查。 2. 静态字段延迟初始化不正确。
什么是最好的方法,
是否正确:
synchronized (Singleton.class) { if (singleton== null) { singleton= new Singleton(); } }
【问题讨论】:
-
这是上述问题的重复;有关详细信息,请参阅该问题。但我不确定这个问题是否有这些有用的链接,所以:About double-checked locking in Java 链接到 these two Java 5 更新。另请参阅 Wikipedia's article on double-checked locking。但对于您的问题的实际答案,请参阅上面链接的问题。
标签: java singleton thread-safety synchronized