Skip to main content
PreparationZone Logo
PrepZone

Thread Safety

Race conditions, what synchronized and volatile each guarantee, and where ThreadLocal fits.

Pass checkpoint below

Why this matters

  • The count++ race is the canonical concurrency bug, and understanding why it happens explains almost every other one.
  • volatile is routinely used where synchronized is required, which produces code that works in testing and fails under load.
  • Thread safety is the most common area for follow-up questions in a backend interview, because the wrong answer is so easy to give confidently.

A race condition

Java
Loading compiler…
Unsynchronised — update lost
A reads 5
B reads 5Before A writes
A writes 6
B writes 6Expected 7
Synchronised — correct
A acquires the lock
A reads 5, writes 6
A releases, B acquires
B reads 6, writes 7
count++ is read, add, write — three steps. Two threads can read the same value before either writes, so one increment disappears. A lock makes the three steps atomic.

count++ compiles to three steps: read the field, add one, write it back. Two threads can read the same value, both compute the same result, and both write it. One increment disappears.

The two problems, separately

  • Atomicity. The read-modify-write sequence can be interleaved. Another thread may act between any two steps.
  • Visibility. Each thread may cache the field in a CPU register or a core-local cache. A write by one thread is not guaranteed to become visible to another without a synchronisation point.

synchronized

Acquiring a monitor gives mutual exclusion and a memory barrier in one.

Java
Loading compiler…

What a monitor guarantees

  • Mutual exclusion — only one thread holds a given monitor at a time, so the block is atomic with respect to other synchronised blocks on the same monitor.
  • Visibility — releasing a monitor flushes the thread's writes; acquiring it invalidates cached reads. Everything done before the release is visible to the next acquirer.
  • Reentrancy — a thread already holding a monitor can acquire it again, which is why one synchronised method may call another.

Both the read and the write must be synchronised. A synchronised increment with an unsynchronised get fixes atomicity and leaves visibility broken.

Instance versus static locks

Java
Loading compiler…

These are different monitors, so an instance method and a static method do not exclude each other.

The rest of this guide is part of Pro

Free covers every fresher guide in full. Pro unlocks Senior, Staff and Architect guides across every track.

Still to come · 6 sections

  • volatile
  • Atomic classes
  • The ABA problem
  • ThreadLocal
  • The hierarchy of solutions
  • Common misreadings

Test yourself

Answer these before moving on — recall is what makes it stick.