forked from github/codeql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathA.java
More file actions
126 lines (117 loc) · 2.39 KB
/
A.java
File metadata and controls
126 lines (117 loc) · 2.39 KB
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
public class A {
public class B {
public int x = 2;
public void setX(int x) {
this.x = x;
}
}
private String s1;
public String getString1() {
if (s1 == null) {
synchronized(this) {
if (s1 == null) {
s1 = "string"; // BAD, immutable but read twice outside sync
}
}
}
return s1;
}
private String s2;
public String getString2() {
String x = s2;
if (x == null) {
synchronized(this) {
x = s2;
if (x == null) {
x = "string"; // OK, immutable and read once outside sync
s2 = x;
}
}
}
return x;
}
private B b1;
public B getter1() {
B x = b1;
if (x == null) {
synchronized(this) {
if ((x = b1) == null) {
b1 = new B(); // BAD, not volatile
x = b1;
}
}
}
return x;
}
private volatile B b2;
public B getter2() {
B x = b2;
if (x == null) {
synchronized(this) {
if ((x = b2) == null) {
b2 = new B(); // OK
x = b2;
System.out.println("OK");
}
}
}
return x;
}
private volatile B b3;
public B getter3() {
if (b3 == null) {
synchronized(this) {
if (b3 == null) {
b3 = new B();
b3.x = 7; // BAD, post update init
}
}
}
return b3;
}
private volatile B b4;
public B getter4() {
if (b4 == null) {
synchronized(this) {
if (b4 == null) {
b4 = new B();
b4.setX(7); // BAD, post update init
}
}
}
return b4;
}
static class FinalHelper<T> {
public final T x;
public FinalHelper(T x) {
this.x = x;
}
}
private FinalHelper<B> b5;
public B getter5() {
if (b5 == null) {
synchronized(this) {
if (b5 == null) {
B b = new B();
b5 = new FinalHelper<B>(b); // BAD, racy read on b5 outside synchronized-block
}
}
}
return b5.x; // Potential NPE here, as the two b5 reads may be reordered
}
private FinalHelper<B> b6;
public B getter6() {
FinalHelper<B> a = b6;
if (a == null) {
synchronized(this) {
a = b6;
if (a == null) {
B b = new B();
a = new FinalHelper<B>(b);
b6 = a; // OK, published through final field with a single non-synced read
}
}
}
return a.x;
}
}