use*_*408 1 java singleton multithreading garbage-collection weak-references
我想达到以下结果:
这是我提出的代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
设计选择包括:
getInstance()方法是synchronized(至MyClass),以便它一次只能由一个线程执行.问题:
getInstance()被评论所在的垃圾收集器打断(意味着垃圾收集器会收回我刚要返回的实例)?如果是这样,我该如何解决呢?保留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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
194 次 |
| 最近记录: |