-
Notifications
You must be signed in to change notification settings - Fork 160
/
FinalExample.java
48 lines (41 loc) · 1.01 KB
/
FinalExample.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
package com.example.concurrency.features.finalcase;
/**
* 描述: 构造函数的错误重排导致线程可能看到 final 变量的值会变
*
* FinalExample
* @link http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html
* @author zed
* @since 2019-06-13 1:38 PM
*/
public class FinalExample {
private static class Global{
private static FinalExample example;
}
private final int x;
private int y;
private static FinalExample f;
// public FinalExample() {
// x = 3;
// y = 4;
// }
public FinalExample() { // bad!
x = 3;
y = 4;
// bad construction - allowing this to escape
Global.example = this;
}
private static void writer() {
f = new FinalExample();
}
private static void reader() {
if (f != null) {
int i = f.x;
int j = f.y;
}
}
public static void main(String[] args) {
writer();
System.out.println(Global.example);
reader();
}
}