Versions Compared

Key

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

...

Wiki Markup
Statically initialized fields are guaranteed to be fully constructed before they are made visible to other threads. (See guidelinerule [TSM03-J. Do not publish partially initialized objects] for more information). Consequently, the background thread must wait for the main (or foreground) thread to finish initialization before it can proceed. However, the {{ConnectionFactory}} class's main thread invokes the {{join()}} method, which waits for the background thread to finish. This interdependency causes a class initialization cycle that results in a deadlock situation \[[Bloch 2005b|AA. Bibliography#Bloch 05b]\].

Similarly, it is inappropriate to start threads from constructors. (See guideline rule TSM01-J. Do not let the (this) reference escape during object construction for more information). Creating timers that perform recurring tasks and starting those timers from within code responsible for initialization introduces liveness issues.

...

Wiki Markup
<ac:structured-macro ac:name="anchor" ac:schema-version="1" ac:macro-id="9f366c922235c365-25559703-4b604613-b7b09fbe-43a8dea6ba9c1ece43d367f1"><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 \[[Grand 2002|AA. Bibliography#Grand 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.

...

This is a singleton class. (See guideline rule MSC16-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 persists for the remainder of the JVM's lifetime. Because the object is managed by a daemon thread, the thread does not hinder a normal shutdown of the JVM.

While the initialization does involve a background thread, that thread does not access any fields or create any liveness or safety issues. Consequently, this code is a safe and useful exception to this guidelinerule.

Risk Assessment

Starting and using background threads during class initialization can result in deadlock conditions.

...

Any vulnerabilities resulting from the violation of this guideline rule are listed on the CERT website.

...