...
Wiki Markup |
---|
<ac:structured-macro ac:name="anchor" ac:schema-version="1" ac:macro-id="92763b0258a0e6cb-aea14534-494e4f54-b01197e4-83b49b65d126a8defe60c979"><ac:parameter ac:name="">CON03-EX1</ac:parameter></ac:structured-macro> *CON03-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 02|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 dereferenced in the future. |
...
This is a singleton class. (See CON23MSC16-J. Address the shortcomings of the Singleton design pattern for more information on how to defensively code singleton classes.) The initialization involves creating a background thread using the current instance of the class. The thread waits indefinitely by invoking Object.wait()
. Consequently, this object exists for the remainder of the Java Virtual Machine's (JVM's) lifetime. Because the object is managed by a daemon thread, the thread does not hinder a normal shutdown of the JVM.
...