Wiki Markup |
---|
Instead of initializing a member object using a constructor, _lazy initialization_ can be used to defer the construction of the member object until an instance is actually required. Lazy initialization also helps in breaking harmful circularities in class and instance initialization, and in performing other optimizations \[[Bloch 2005|AA. Bibliography#Bloch 05]\]. |
...
Wiki Markup |
---|
According to Pugh \[[Pugh 2004|AA. Bibliography#Pugh 04]\]: |
... writes that initialize the
Helper
object and the write to thehelper
field can be done or perceived out of order. As a result, a thread which invokesgetHelper()
could see a non-null reference to ahelper
object, but see the default values for fields of thehelper
object, rather than the values set in the constructor.Even if the compiler does not reorder those writes, on a multiprocessor, the processor or the memory system may reorder those writes, as perceived by a thread running on another processor.
...
Variables that are declared static and initialized at declaration, or from a static initializer, are guaranteed to be fully constructed before being made visible to other threads.
Compliant Solution (Initialize-on-
...
Demand, Holder Class Idiom)
This compliant solution uses the initialize-on-demand, holder class idiom that implicitly incorporates lazy initialization by declaring a static variable within a static Holder
inner class.
...
In this compliant solution, the Helper
class is immutable and, consequently, guaranteed to be fully constructed before becoming visible. In this case, there are no further requirements to ensure that the double-checked locking idiom does not result in the publication of an uninitialized or partially initialized field.
...
Wiki Markup |
---|
*LCK10-EX1:* The noncompliant form of the double-checked locking idiom can be used for 32-bit primitive values (for example, {{int}} or {{float}}) \[[Pugh 2004|AA. Bibliography#Pugh 04]\]. Note that it does not work for {{long}} or {{double}} because unsynchronized reads/writes of 64-bit primitives are not guaranteed to be atomic. (seeSee guideline [VNA05-J. Ensure atomicity when reading and writing 64-bit values].) |
...