Java Memory Model Deep Dive #1855
-
|
Q: Explain happens-before relationship with real multithreading examples. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
Guarantees visibility + ordering between threads in Java Memory Model.
int x = 10; ➡️ start() happens-before thread execution
int x = 0; ➡️ thread completion happens-before join()
volatile boolean flag = false; Thread 1: flag = true; ➡️ write → read has happens-before
synchronized(lock) { x = 10; } // Thread 1 ➡️ unlock happens-before next lock
AtomicInteger a = new AtomicInteger(0); ➡️ uses memory barriers internally TL;DR: |
Beta Was this translation helpful? Give feedback.
Guarantees visibility + ordering between threads in Java Memory Model.
int x = 10;
new Thread(() -> {
System.out.println(x); // always sees 10
}).start();
➡️ start() happens-before thread execution
int x = 0;
Thread t = new Thread(() -> x = 5);
t.start();
t.join();
System.out.println(x); // always 5
➡️ thread completion happens-before join()
volatile boolean flag = false;
Thread 1: flag = true;
Thread 2: if(flag) { /* guaranteed visible */ }
➡️ write → read has happens-before
synchronized(lock) { x = 10; } // Thread 1
synchronized(lock) { print(x); } // Thread 2 → sees 10
➡️ unlock happens-before next lock
AtomicInte…