forked from benelog/java-concurrency
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Initialization.java
52 lines (43 loc) · 1.62 KB
/
Initialization.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package ej2.item71;
// Initialization styles - Pages 282-284
public class Initialization {
// Normal initialization of an instance field - Page 282
private final FieldType field1 = computeFieldValue();
// Lazy initialization of instance field - synchronized accessor - Page 282
private FieldType field2;
synchronized FieldType getField2() {
if (field2 == null)
field2 = computeFieldValue();
return field2;
}
// Lazy initialization holder class idiom for static fields - Page 283
private static class FieldHolder {
static final FieldType field = computeFieldValue();
}
static FieldType getField3() { return FieldHolder.field; }
// Double-check idiom for lazy initialization of instance fields - Page 283
private volatile FieldType field4;
FieldType getField4() {
FieldType result = field4;
if (result == null) { // First check (no locking)
synchronized(this) {
result = field4;
if (result == null) // Second check (with locking)
field4 = result = computeFieldValue();
}
}
return result;
}
// Single-check idiom - can cause repeated initialization! - Page 284
private volatile FieldType field5;
private FieldType getField5() {
FieldType result = field5;
if (result == null)
field5 = result = computeFieldValue();
return result;
}
private static FieldType computeFieldValue() {
return new FieldType();
}
}
class FieldType { }