Sobes.tech
Junior — Middle

Can you explain the concept of happens-before in Java and its role in ensuring thread safety?

sobes.tech AI

Answer from AI

In Java, the happens-before concept defines the order of visibility and execution of operations between threads. If operation A happens-before operation B, then all changes made in A are guaranteed to be visible in B.

This is a key mechanism for ensuring thread safety, as without it, one thread may not see the changes made by another.

Examples of happens-before relationships:

  • Operations within a single thread are executed in program order.
  • Unlock() on a monitor happens-before the subsequent lock() on the same monitor.
  • Writing to a volatile variable happens-before subsequent reading of that variable.

For example, if one thread writes a value to a volatile variable, and another reads it, the second thread will see all changes made before the write.

volatile int flag = 0;
int data = 0;

// Thread 1
data = 42;
flag = 1; // write to volatile

// Thread 2
if (flag == 1) {
    // will guaranteedly see data == 42
    System.out.println(data);
}

Thus, happens-before helps prevent issues with caching and instruction reordering, ensuring correct synchronization between threads.