我想达到以下结果:
这是我提出的代码:
public final class MyClass {
private static WeakReference<MyClass> instance;
public static synchronized MyClass getInstance() {
if ((instance == null) || (instance.get() == null)) {
instance = new WeakReference<MyClass>(new MyClass());
}
// TODO what if GC strikes here?
return instance.get();
}
}
设计选择是:
getInstance()
方法为synchronized
(至MyClass
),因此一次只能由一个线程执行。问题:
getInstance()
被评论所在的垃圾收集器打断(意味着垃圾收集器会收回我刚刚要返回的实例)?如果是这样,我该如何解决它呢?答案 0 :(得分:6)
在变量中保留MyClass
的本地副本,而不是仅将您的引用副本提供给WeakRefrence
的构造函数。这将阻止GC在instance
调用和返回函数之间收集new WeakReference<MyClass>
。
public final class MyClass {
private static WeakReference<MyClass> instance;
public static synchronized MyClass getInstance() {
MyClass classInstance = null;
if (instance != null) {
classInstance = instance.get();
if(classInstance != null)
{
return classInstance;
}
}
classInstance = new MyClass();
instance = new WeakReference<MyClass>(classInstance);
//This is now a strong reference and can't be GC'ed between the previous line and this one.
return classInstance;
}
}