How does happens-before relationships behave in multithreaded code?

In multithreaded programming, the happens-before relationship is a key concept that defines visibility and ordering between operations performed by different threads. It ensures that memory writes by one specific statement are visible to another specific statement when executed by different threads.

The Java Memory Model (JMM) establishes happens-before relationships, which are crucial for ensuring that threads interact correctly without introducing race conditions. If one operation happens-before another, then the first is visible and ordered before the second in all threads.

Some key rules include:

  • Program order rule: Each action in a single thread happens-before every action that comes later in that thread.
  • Monitor lock rule: An unlock on a monitor lock happens-before every subsequent lock on that same monitor.
  • Thread start rule: The start() method on a thread happens-before any actions in the thread.
  • Thread join rule: All actions in a thread happen-before any thread that successfully returns from a join() on that thread.

Here's an example demonstrating happens-before relationships with threads:

// Java Example class SharedResource { private int counter = 0; public synchronized void increment() { counter++; } public synchronized int getCounter() { return counter; } } public class Example { public static void main(String[] args) { SharedResource resource = new SharedResource(); Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { resource.increment(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { resource.increment(); } }); t1.start(); // Thread t1 starts t2.start(); // Thread t2 starts try { t1.join(); // Main thread waits for t1 to finish t2.join(); // Main thread waits for t2 to finish } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Final Counter: " + resource.getCounter()); } }

multithreading happens-before Java Memory Model memory visibility synchronization