| 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. Bibliography#BlochReferences#Bloch 05b]\]. Consequently, programs must ensure that class initialization is complete before starting any threads. |
...
| Wiki Markup |
|---|
Statically initialized fields are guaranteed to be fully constructed before they are made visible to other threads (see rule [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#BlochReferences#Bloch 05b]\]. |
Similarly, it is inappropriate to start threads from constructors (see 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 also introduces liveness issues.
...
| Wiki Markup |
|---|
<ac:structured-macro ac:name="anchor" ac:schema-version="1" ac:macro-id="90ebbdcec36980eb-a2e034f5-4fe04103-89769d33-e1476b8c90123018f58b974d"><ac:parameter ac:name="">CON20-EX1</ac:parameter></ac:structured-macro> *TSM02-EX0:* Programs are permitted to start a background thread (or threads) during class initialization, provided the thread cannot access any fields. For example, the following {{ObjectPreserver}} class (based on \[[Grand 2002|AA. Bibliography#GrandReferences#Grand 02]\]) provides a mechanism for storing object references, which prevents an object from being garbage-collected even when the object is never again dereferenced. |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="10326d0f7d1ce6c8-bc6542a8-48594325-8f64b59e-685065755fbba3957958dee0"><ac:plain-text-body><![CDATA[ | [[Bloch 2005b | AA. Bibliography#Bloch References#Bloch 05b]] | 8, Lazy Initialization | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="68e2ba978077967b-756328ae-4a044d4d-b1888651-2017172cb5124ecd60e465ed"><ac:plain-text-body><![CDATA[ | [[Grand 2002 | AA. Bibliography#Grand References#Grand 02]] | Chapter 5, Creational Patterns, Singleton | ]]></ac:plain-text-body></ac:structured-macro> |
...