Sobes.tech
Senior

Does volatile guarantee happens-before?

sobes.tech AI

Answer from AI

The key property of volatile in Java is ensuring the visibility of variable changes between threads, but it does not guarantee full happens-before semantics for all operations.

Specifically:

  • Writing to a volatile variable happens-before subsequent reading of that same variable from another thread.
  • This means that changes made before writing to a volatile variable will be visible to the thread that reads this variable.

However, volatile does not ensure atomicity of complex operations (e.g., increment), and does not guarantee happens-before between other actions unrelated to volatile.

Example:

volatile int flag = 0;
int data = 0;

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

// Thread 2
if (flag == 1) { // volatile read
    // will guaranteedly see data == 42
}

Thus, volatile provides happens-before between the write and read of the volatile variable itself, ensuring visibility, but does not replace full synchronization for complex scenarios.