Sobes.tech
Senior

What is happens-before? Why is i++ unsafe without synchronization?

sobes.tech AI

Answer from AI

Happens-before is a relation between operations in multithreaded programming that guarantees one operation is visible and occurs before another. In Java, it is a key concept for ensuring correct synchronization and visibility of changes between threads.

The operation i++ is not atomic: it consists of three steps — reading the value of i, incrementing by 1, and writing back. Without synchronization, two threads can read the same value of i simultaneously, increment it, and write it back, leading to lost updates.

Without happens-before guarantees, changes made by one thread may not be visible to another, and operations can be executed in arbitrary order due to compiler and processor optimizations.

Example of a problem:

class Counter {
  int i = 0;

  void increment() {
    i++; // not atomic
  }
}

If multiple threads call increment() without synchronization, the final value of i may be less than expected.

To ensure correctness, mechanisms like synchronized, volatile, AtomicInteger, or others that provide happens-before guarantees and atomicity should be used.

What is happens-before? Why is i++ unsafe without… - sobes.tech