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]. Consequently, programs must ensure that class initialization is complete before starting any threads.
...
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].
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.
...
Anchor | ||||
---|---|---|---|---|
|
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]) provides a mechanism for storing object references, which prevents an object from being garbage-collected even when the object is never again dereferenced....
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
TSM02-J | low | probable | high | P2 | L3 |
Bibliography
8, Lazy Initialization | |
Chapter 5, Creational Patterns, Singleton |
...
Tasklist | ||||
---|---|---|---|---|
| ||||
||Completed||Priority||Locked||CreatedDate||CompletedDate||Assignee||Name|| |T|M|F|1269649993019|1269700561582|rcs_mgr|"Starting and using background threads during class initialization can result in class initialization cycles and deadlock. *For instance,* the main thread responsible for performing class initialization *may* block waiting for the background thread, which in turn will wait for the main thread to finish class initialization." ... see suggested words in bold...I am also generally unsure about the use of "can" vs. "may" because deadlocks are a "possibility" so perhaps "may" should be used?| |
...