...
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 HashSet protectedSet = new HashSet(); private ObjectPreserver() { new Thread(this).start(); // keeps the reference alive } public synchronized void run(){ try { wait(); }catch(InterruptedException e) { e.printStackTrace();} } // OnjectsObjects passed to this method will be preserved until // the unpreserveObject method is called public static void preserveObject(Object o) { protectedSet.add(o); } // Unprotect the objects so that they can be garbage collected public static void unpreserveObject(Object o) { protectedSet.remove(o); } } |
...