Wiki Markup |
---|
Starting and using background threads during class initialization can result in class initialization cycles and deadlock. For example, the main thread responsible for performing class initialization can block waiting for the background thread, which, in turn, will wait for the main thread to finish class initialization. This issue can arise, for example, when a database connection is established in a background thread during class initialization \[[Bloch 2005b|AA. Java References#BlochBibliography#Bloch 05b]\]. |
Noncompliant Code Example (Background Thread)
...
Wiki Markup |
---|
Statically initialized fields are guaranteed to be fully constructed before they are made visible to other threads. (See guideline [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. Java References#BlochBibliography#Bloch 05b]\]. |
Similarly, it is inappropriate to start threads from constructors. (See guideline 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="6631ab2fe19a90ac-09122038-497d49ab-92de9143-fe849c408a6b03eee778c6c8"><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#PatternsBibliography#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. |
...
Wiki Markup |
---|
\[[Bloch 2005b|AA. Java References#BlochBibliography#Bloch 05b]\] 8. "Lazy Initialization" \[[Patterns 2002|AA. Java References#PatternsBibliography#Patterns 02]\] Chapter 5, Creational Patterns, Singleton |
...