Memory model · Topic 2 of 5
Happens-before
Definition​
"Happens-before" is the rule that says when one thread is guaranteed to see what another thread wrote. Starting a thread, joining it, releasing a lock and writing a volatile field all create such a guarantee. Without one, a thread may see old values.
Example code​
start() and join() make writes visible
class Demo {
static int result; // a plain field: no volatile, no lock
public static void main(String[] args) throws InterruptedException {
result = 10; // written before start(): the new thread is guaranteed to see it
Thread worker = new Thread(() -> {
System.out.println("worker sees " + result);
result = result * 2; // written by the worker
});
worker.start();
worker.join(); // join() makes the worker's writes visible to main
System.out.println("main sees " + result);
}
}
// Output:
// worker sees 10
// main sees 20
Finished this page? Track your progress (saved only in your browser).