Skip to content

Commit 05e745a

Browse files
authored
Better example in LI.3, fixes code-review-checklists#1
1 parent 4e2da9f commit 05e745a

File tree

1 file changed

+10
-8
lines changed

1 file changed

+10
-8
lines changed

README.md

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -205,23 +205,25 @@ Was it considered to **use one of the array-based queues from [the JCTools libra
205205

206206
If the initialized objects are immutable a more efficient [UnsafeLocalDCL](http://hg.openjdk.java.net/code-tools/jcstress/file/9270b927e00f/tests-custom/src/main/java/org/openjdk/jcstress/tests/singletons/UnsafeLocalDCL.java#l71) pattern might also be used. However, if the lazily-initialized field is not `volatile` and there are accesses to the field that bypass the initialization path, the value of the **field must be carefully cached in a local variable**. For example, the following code is buggy:
207207

208-
private MyClass lazilyInitializedField;
208+
private MyImmutableClass lazilyInitializedField;
209209

210-
void cleanup() {
211-
if (lazilyInitializedField != null) { // (1)
210+
void doSomething() {
211+
...
212+
if (lazilyInitializedField != null) { // (1)
212213
// Can throw NPE!
213-
lazilyInitializedField.close(); // (2)
214+
lazilyInitializedField.doSomethingElse(); // (2)
214215
}
215216
}
216217

217-
It might result in a `NullPointerException`, because although a non-null value is observed when the field is read the first time at line 1, the second read at line 2 could observe null.
218+
This code might result in a `NullPointerException`, because although a non-null value is observed when the field is read the first time at line 1, the second read at line 2 could observe null.
218219

219220
The above code could be fixed as follows:
220221

221-
void cleanup() {
222-
MyClass lazilyInitialized = this.lazilyInitializedField;
222+
void doSomething() {
223+
MyImmutableClass lazilyInitialized = this.lazilyInitializedField;
223224
if (lazilyInitialized != null) {
224-
lazilyInitialized.close();
225+
// Calling doSomethingElse() on a local variable
226+
lazilyInitialized.doSomethingElse();
225227
}
226228
}
227229

0 commit comments

Comments
 (0)