How do you use happens-before relationships with a simple code example?

The happens-before relationship is a key concept in the Java Memory Model that defines the visibility of memory operations across different threads. If one action happens-before another, the results of the first action are visible to the second action. This concept is crucial for writing thread-safe code without using excessive synchronization.

Example of Happens-Before Relationship

In the example below, we have two threads: one that writes a value to a shared variable, and another that reads that value. The volatile keyword creates a happens-before relationship between the write and the read, ensuring visibility.

import java.util.concurrent.atomic.AtomicInteger; public class HappensBeforeExample { private static AtomicInteger sharedValue = new AtomicInteger(0); private static volatile boolean flag = false; public static void main(String[] args) { Thread writer = new Thread(() -> { sharedValue.set(42); // Write to shared variable flag = true; // Set flag to true }); Thread reader = new Thread(() -> { if (flag) { // Check flag System.out.println(sharedValue.get()); // Read from shared variable } }); writer.start(); reader.start(); } }

happens-before Java Memory Model thread safety concurrency volatile shared variables