-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryVisibilityDemo.java
More file actions
76 lines (63 loc) · 2.53 KB
/
MemoryVisibilityDemo.java
File metadata and controls
76 lines (63 loc) · 2.53 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
// 10. MEMORY VISIBILITY / DATA CORRUPTION - Changes not visible due to caching
// Problem: One thread's changes may not be visible to another due to compiler optimizations
public class MemoryVisibilityDemo {
static class Flag {
private boolean flag = false; // NOT volatile!
private int value = 0;
// Writer thread
public void writeWithoutVolatile() {
value = 42;
flag = true; // Signal that value is ready
System.out.println("Writer: Set value=42, flag=true");
}
// Reader thread
public void readWithoutVolatile() {
int localValue = 0;
while (!flag) {
// Compiler may optimize this away!
// It might cache flag in a register and never re-read it
}
localValue = value;
System.out.println("Reader: Got value=" + localValue);
}
}
static class FlagVolatile {
private volatile boolean flag = false; // VOLATILE - guarantees visibility
private volatile int value = 0;
// Writer thread
public void writeWithVolatile() {
value = 42;
flag = true; // Guaranteed to be visible to other threads
System.out.println("Writer: Set value=42, flag=true (VOLATILE)");
}
// Reader thread
public void readWithVolatile() {
int localValue = 0;
while (!flag) {
// Volatile ensures we re-read flag every time
}
localValue = value;
System.out.println("Reader: Got value=" + localValue + " (VOLATILE)");
}
}
public static void main(String[] args) throws InterruptedException {
System.out.println("=== WITHOUT VOLATILE ===");
Flag flagObj = new Flag();
Thread reader1 = new Thread(flagObj::readWithoutVolatile);
Thread writer1 = new Thread(flagObj::writeWithoutVolatile);
reader1.start();
Thread.sleep(100);
writer1.start();
reader1.join();
writer1.join();
System.out.println("\n=== WITH VOLATILE ===");
FlagVolatile flagObjVolatile = new FlagVolatile();
Thread reader2 = new Thread(flagObjVolatile::readWithVolatile);
Thread writer2 = new Thread(flagObjVolatile::writeWithVolatile);
reader2.start();
Thread.sleep(100);
writer2.start();
reader2.join();
writer2.join();
}
}