...
| Wiki Markup |
|---|
<ac:structured-macro ac:name="anchor" ac:schema-version="1" ac:macro-id="598bb3cd0255a5b0-c0f6136b-49184d0e-afccbbef-26e88deb6343a368c2dcc62b"><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 | ||
|---|---|---|
| ||
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);
}
}
|
...