Wiki Markup |
---|
_Lazy initialization_ defers the construction of a member field or an object referred to by a member field until an instance is actually required, rather than computing the field value or constructing the referenced object in the class's constructor. Lazy initialization also helps to break harmful circularities in class and instance initialization and in performing other optimizations \[[Bloch 2005|AA. Bibliography#Bloch 05]\]. |
...
Code Block | ||
---|---|---|
| ||
// Correct multithreaded version using synchronization final class Foo { private Helper helper = null; public synchronized Helper getHelper() { if (helper == null) { helper = new Helper(); } return helper; } // ... } |
The double-checked locking idiom improves performance by limiting synchronization to the rare case of computing the field's value or constructing a new instance for the field to reference, and by foregoing synchronization during the common case of retrieving an already-created instance or value.
...
Code Block | ||
---|---|---|
| ||
// "Double-Checked Locking" idiom
final class Foo {
private Helper helper = null;
public Helper getHelper() {
if (helper == null) {
synchronized (this) {
if (helper == null) {
helper = new Helper();
}
}
}
return helper;
}
// Other methods and members...
}
|
...
... 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.
Also see rule This code also violates TSM03-J. Do not publish partially initialized objects.
Compliant Solution (
...
volatile
)
This compliant solution declares the helper
field volatile.
Code Block | ||
---|---|---|
| ||
// Works with acquire/release semantics for volatile // Broken under JDK 1.4 and earlier final class Foo { private volatile Helper helper = null; public Helper getHelper() { if (helper == null) { synchronized (this) { if (helper == null) { helper = new Helper(); // If the helper is null, create a new instance } } } return helper; // If helper is non-null, return its instance } } |
Wiki Markup |
---|
When a thread initializes the {{Helper}} object, a [happens-before relationship|BB. Definitions#happens-before order] is established between this thread and any other thread that retrieves and returns the instance \[[Pugh 2004|AA. Bibliography#Pugh 04], [Manson 2004|AA. Bibliography#Manson 04]\]. |
...
In this compliant solution, suppose that the Helper
class is immutable. The JMM guarantees that immutable objects are fully constructed before they become visible to any other thread. Additionally, the block synchronization in the getHelper()
method suffices to ensure that all methods that can see a non-null value of the helper
field have a proper happens-before relationship for the update to the helper
reference. This synchronization and the aforementioned JMM guarantee combine to ensure that only fully-initialized Helper
objects are visible to threads that see non-null values. Consequently, this compliant solution correctly creates both of the needed happens-before relationships.
Code Block | ||
---|---|---|
| ||
public final class Helper { private final int n; public Helper(int n) { this.n = n; } // Other fields and methods, all fields are final } final class Foo { private Helper helper = null; public Helper getHelper() { if (helper == null) { synchronized (this) { if (helper == null) { helper = new Helper(42); // If the helper is null, create a new instance } } } return helper; // If helper is non-null, return its instance } } |
Exceptions
Wiki Markup |
---|
*LCK10-EX0:* Use of the noncompliant form of the double-checked locking idiom is permitted for 32-bit primitive values (for example, {{int}} or {{float}}) \[[Pugh 2004|AA. Bibliography#Pugh 04]\], although this usage is discouraged. The noncompliant form establishes the necessary happens-before relationship between threads that see an initialized version of the primitive value. The second happens-before relationship (that for the initialization of the fields of the referent) is moot, because unsynchronized reads and writes of primitive values up to 32-bits are guaranteed to be atomic. Consequently, the noncompliant form establishes the only needed happens-before relationship in this case. Note, however, that the noncompliant form fails for {{long}} or {{double}} because unsynchronized reads/writes of 64-bit primitives lack a guarantee of atomicity, and thus require a second happens-before relationship to guarantee that all threads see only fully assigned 64-bit values (See rule [VNA05-J. Ensure atomicity when reading and writing 64-bit values].) |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="0930d04397c528af-1d328d3b-4c334e25-addb97d1-70afed5b651796ae7198b654"><ac:plain-text-body><![CDATA[ | [[API 2006 | AA. Bibliography#API 06]] |
| ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="83b7a97cbf206109-b882254a-4b7d44c2-967d813d-976942d864b11a51ffbd005c"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. Bibliography#JLS 05]] | Section 12.4, "Initialization of Classes and Interfaces" | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="e1a1917865ff4066-d584f4ec-44fa40ee-a233b266-c2ad473cc4caab67af9c6848"><ac:plain-text-body><![CDATA[ | [[Pugh 2004 | AA. Bibliography#Pugh 04]] |
| ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="e5f1495372b7fb54-83bdd258-4f7448f1-8b8caec8-223839283d2ade9064748d67"><ac:plain-text-body><![CDATA[ | [[Bloch 2001 | AA. Bibliography#Bloch 01]] | Item 48: "Synchronize access to shared mutable data" | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="c334b192bddd1f8b-833d4601-49b64570-9c498b06-99af9adf45a66f6c8b227f05"><ac:plain-text-body><![CDATA[ | [[Bloch 2008 | AA. Bibliography#Bloch 08]] | Item 71: "Use lazy initialization judiciously"]]></ac:plain-text-body></ac:structured-macro> |
...