我想在Java中实现多线程的延迟初始化.
我有一些类似的代码:
class Foo {
private Helper helper = null;
public Helper getHelper() {
if (helper == null) {
Helper h;
synchronized(this) {
h = helper;
if (h == null)
synchronized (this) {
h = new Helper();
} // release inner synchronization lock
helper = h;
}
}
return helper;
}
// other functions and members...
}
Run Code Online (Sandbox Code Playgroud)
而且我得到了"Double-Checked Locking is Broken"声明.
我怎么解决这个问题?
创建单身人士的模式似乎是这样的:
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton(){
}
public static Singleton getInstance()
{
return instance;
}
}
Run Code Online (Sandbox Code Playgroud)
但是我的问题是如果Singleton构造函数执行非单元测试友好的事情,例如调用外部服务,jndi查找等,你如何使用这样的类.
我想我可以重构它:
public class Singleton {
private static Singleton instance;
private Singleton(){
}
public synchronized static Singleton getInstance()
{
if(instance == null)
instance = new Singleton();
return instance;
}
//for the unit tests
public static void setInstance(Singleton s)
{
instancce = s;
}
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是,仅仅为了单元可测试性,我已经强制getInstance被同步,因此只是对于测试方面,它将对实际应用程序产生负面影响.有没有办法解决它,似乎任何其他类型的延迟初始化将无法工作,因为java中双锁模式的破坏性质.
我正在尝试找出以下 MC 问题的答案。我尝试在谷歌上寻找答案,但人们似乎对这个问题有不同的答案。有人可以解释一下他们的答案吗?
public class Gingleton {
private static Gingleton INSTANCE = null;
public static Gingleton getInstance()
{
if ( INSTANCE == null )
{
INSTANCE = new Gingleton();
}
return INSTANCE;
}
private Gingleton() {
}
}
Run Code Online (Sandbox Code Playgroud)
可以创建多个 Gingleton 实例(我的选择)
Gingleton 永远不会被创建
构造函数是私有的,不能被调用
value 可以被垃圾回收,调用 getInstance 可能会返回垃圾数据