I want to achieve the following results:
This is the code I came up with:
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();
}
}
Design choices were:
getInstance()
method is synchronized
(to MyClass
) so that it can only be executed by one thread at a time.Questions:
getInstance()
getting interrupted by the garbage collector where the comment is (meaning the garbage collector would reclaim the instance I was just about to return)? If so, how can I work around it?Hold a local copy of MyClass
in a variable instead of just giving your only copy of the reference in to the constructor of WeakRefrence
. This will prevent the GC from collecting instance
between the new WeakReference<MyClass>
call and the function returning.
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;
}
}