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 initializing computing the field value or constructing the memberreferenced object in the class's constructor. Lazy initialization also helps to breakingbreak harmful circularities in class and instance initialization and in performing other optimizations \[[Bloch 2005|AA. Bibliography#Bloch 05]\]. |
...
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 creationfor the field to reference, and by foregoing synchronization during the common case of retrieving an already-created instance or value.
Incorrect forms of the double-checked idiom include those that allow publication of an uninitialized or partially initialized object. Consequently, use of incorrect only those forms of the double-checked locking idiom is forbiddenthat correctly establish a happens-before relationship both for the helper
reference and also for the complete construction of the Helper
instance are permitted.
Noncompliant Code Example
...
Wiki Markup |
---|
Initialization of the static {{helper}} field is deferred until the {{getInstance()}} method is called. ThisThe idiomnecessary ishappens-before arelationships betterare choicecreated thanby the double-checkedcombination lockingof idiomthe forclass lazily loader's actions loading and initializing static fields \[[Bloch 2008|AA. Bibliography#Bloch 08]\]. However, this idiom cannot be used to lazily initialize instance fields the {{Holder}} instance, and the guarantees provided by the Java memory model. This idiom is a better choice than the double-checked locking idiom for lazily initializing static fields \[[Bloch 20012008|AA. Bibliography#Bloch 0108]\]. |
Compliant Solution (ThreadLocal
Storage)
Wiki Markup |
---|
This compliant solutionHowever, (originallythis suggestedidiom bycannot Alexanderbe Terekhov \used to lazily initialize instance fields \[[PughBloch 20042001|AA. Bibliography#PughBibliography#Bloch 0401]\]. |
Compliant Solution (ThreadLocal
Storage)
...
Wiki Markup |
---|
This compliant solution (originally suggested by Alexander Terekhov \[[Pugh 2004|AA. Bibliography#Pugh 04]\]) uses a {{ThreadLocal}} object to track whether each individual thread has participated in the synchronization that creates the needed happens-before relationships. Each thread stores a non-null value into its thread-local {{perThreadInstance}} only inside the synchronized {{createHelper()}} method; consequently, any thread that sees a null value must establish the necessary happens-before relationships by invoking {{createHelper()}}. |
Code Block | ||
---|---|---|
| ||
final class Foo {
private final ThreadLocal<Foo> perThreadInstance = new ThreadLocal<Foo>();
private Helper helper = null;
public Helper getHelper() {
if (perThreadInstance.get() == null) {
createHelper();
}
return helper;
}
private synchronized void createHelper() {
if (helper == null) {
helper = new Helper();
}
// Any non-null value can be used as an argument to set()
perThreadInstance.set(this);
}
}
|
Compliant Solution (Immutable)
In this compliant solution, 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-EX1:* 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, |
Code Block | ||
---|---|---|
| ||
final class Foo {
private final ThreadLocal<Foo> perThreadInstance = new ThreadLocal<Foo>();
private Helper helper = null;
public Helper getHelper() {
if (perThreadInstance.get() == null) {
createHelper();
}
return helper;
}
private synchronized void createHelper() {
if (helper == null) {
helper = new Helper();
}
// Any non-null value can be used as an argument to set()
perThreadInstance.set(this);
}
}
|
Compliant Solution (Immutable)
In this compliant solution, the Helper
class is immutable and, consequently, is guaranteed to be fully constructed before becoming visible. In this case, lacks any further requirements to ensure that the double-checked locking idiom avoids the publication of an uninitialized or partially initialized field.
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-EX1:* 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. Note that the noncompliant form fails for {{long}} or {{double}} because unsynchronized reads/writes of 64-bit primitives are 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].) |
...
Using incorrect forms of the double-checked , locking idiom can lead to synchronization problems and can expose partially-initialized objects.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
LCK10-J | low | probable | medium | P4 | L3 |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="f7a4d60aa0b3c332-a2a47576-4e564f6f-b9a997de-5ed3548e74eb207902870075"><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="b0fc4de61db0c32f-58a34cc0-4911410b-a777bc7f-21919983a483a5bad7ade8aa"><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="533effecfe653a83-d658122c-4be646db-b81fb26c-10b7ffa5f0790ab20a367855"><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="42bfe3356d16d926-89cab121-4e814158-9a8db8e8-c875e31694a1e4fc093d8514"><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="2331e0e20b174e07-cc87adae-48bd4f86-a069a78c-422a49500cadae934d86b514"><ac:plain-text-body><![CDATA[ | [[Bloch 2008 | AA. Bibliography#Bloch 08]] | Item 71: "Use lazy initialization judiciously"]]></ac:plain-text-body></ac:structured-macro> |
...