...
Code Block | ||
---|---|---|
| ||
{ MySingleton ms1 = MySingleton.getInstance(); // ... } MySingleton ms2 = MySingleton.getInstance(); |
This problem can particularly manifest in state bearing singletons.
Compliant Solution (prevent garbage collection)
...
Code Block |
---|
public class ObjectPreserver implements Runnable { private static ObjectPreserver lifeLine = new ObjectPreserver(); // Neither this class, nor HashSet will be garbage collected. // References from HashSet to other objects will also exhibit this property private static HashMap<Integer,Object> protectedMap = new HashMap<Integer,Object>(); private ObjectPreserver() { new Thread(this).start(); // keeps the reference alive } public synchronized void run(){ try { wait(); } catch(InterruptedException e) { /* Forward to handler */ } } // Objects passed to this method will be preserved until // the unpreserveObject method is called public static void preserveObject(Object oobj) { protectedMap.getput(0, obj); } // Returns the same instance every time public static Object getObject() { return protectedMap.get(0); } // Unprotect the objects so that they can be garbage collected public static void unpreserveObject() { protectedMap.remove(0); } } |
...