Versions Compared

Key

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

...

Wiki Markup
<ac:structured-macro ac:name="anchor" ac:schema-version="1" ac:macro-id="5f38ac287d6c96f0-aa6cf3fa-47ac4f9c-a7a7a2b4-6842b636edc705e6218fc144"><ac:parameter ac:name="">CON20-EX1</ac:parameter></ac:structured-macro>
*TSM02-EX1:* It is permissible to start a background thread during class initialization provided the thread does not access any fields. For example, the {{ObjectPreserver}} class (based on \[[Patterns 2002|AA. Java References#Patterns 02]\]) shown below provides a mechanism for storing object references, which prevents an object from being garbage-collected, even if the object is not de-referenced in the future.

Code Block
bgColor#ccccff
public final class ObjectPreserver implements Runnable {
  private static final ObjectPreserver lifeLine = new ObjectPreserver();

  private ObjectPreserver() {
    Thread thread = new Thread(this);
    thread.setDaemon(true);
    thread.start(); // Keep this object alive
  }

  // Neither this class nor HashMap will be garbage-collected.
  // References from HashMap to other objects will also exhibit this property
  private static final ConcurrentHashMap<Integer,Object> protectedMap
    = new ConcurrentHashMap<Integer,Object>();

  public synchronized void run() {
    try {
      wait();
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt(); // Reset interrupted status
    }
  }

  // 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);
  }
}

...