forked from Java2ArkTS/Java2ArkTS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInconsistentReadDemo.java
More file actions
38 lines (32 loc) · 1.07 KB
/
Copy pathInconsistentReadDemo.java
File metadata and controls
38 lines (32 loc) · 1.07 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
public class InconsistentReadDemo {
int count = 1;
public static void main(String[] args) {
InconsistentReadDemo demo = new InconsistentReadDemo();
Thread thread = new Thread(new ConcurrencyCheckTask(demo));
thread.start();
while (true) {
demo.count++;
}
}
}
class ConcurrencyCheckTask implements Runnable {
private InconsistentReadDemo demo;
public ConcurrencyCheckTask(InconsistentReadDemo demo) {
this.demo = demo;
}
public void run() {
int c = 0;
for (int i = 0; ; i++) {
// 2 consecutive reads in the same thread
int c1 = demo.count;
int c2 = demo.count;
if (c1 != c2) {
c++;
// On my dev machine,
// a batch of inconsistent reads can be observed when the process starts
System.err.printf("Inconsistent read observed!! Check time=%s, Occurrence=%s (%s%%), 1=%s, 2=%s%n",
i + 1, c, (float) c / (i + 1) * 100, c1, c2);
}
}
}
}