Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
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);
  }
}

...