Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: changed HashMap to ConcurrentHashMap

...

Wiki Markup
*CON03:EX1*: The {{ObjectPreserver}} class (based on \[[Patterns 02|AA. Java References#Patterns 02]\]) is shown below: This class provides a mechanism for storing object references, which prevents an object from being garbage-collected, even if the remaining program no longer maintains a reference to the object.

Code Block
bgColor#ccccff
import java.util.HashMap;

public class ObjectPreserver implements Runnable {
  private static ObjectPreserver lifeLine = new ObjectPreserver();

  private ObjectPreserver() {
    Thread thread = new Thread( this);
    thread.setDaemon( true);
    thread.start(); // keep this object alive
  }
 
  // Neither this class, nor HashSet will be garbage collected.
  // References from HashMap to other objects will also exhibit this property
  private static final HashMap<IntegerConcurrentHashMap<Integer,Object> protectedMap 
    = new HashMap<IntegerConcurrentHashMap<Integer,Object>();
  
  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 obj) {    
    protectedMap.put(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);
  }
}

...