Thread Interference in Java
Fast recall
Quick revision
Core answer
counter++. Use an atomic operation or protect the complete read-modify-write with the same lock.Deeper understanding of how operations interleave at the CPU and bytecode level
Assuming single-statement Java code is always atomic — not knowing that counter-plus-plus is three operations
Walk through the exact bytecode-level interleaving that causes a lost update in a counter increment
Interview-ready guide
Interview answer
Thread interference is the concrete overlap that can produce a race condition. Suppose two threads increment the same int. Each increment must read a value, calculate the next one, and store it. If both read 10 before either completes, both can store 11 and one update is lost.
The exact number of bytecode or CPU instructions is not the rule to remember; compilers and JVM implementations can differ. The language-level rule is that counter++ is not an atomic operation. I would use AtomicInteger.incrementAndGet() for an independent counter, or one synchronized region when the counter changes together with other state. Marking the field volatile would make plain reads and writes visible but would not make the read-modify-write indivisible.
Thread Interference in Java
Direct Answer
Thread interference is one form of race condition: steps from operations on the same shared data interleave and one operation disturbs another. A common example is a lost update when two threads execute counter++. Use an atomic operation or protect the complete read-modify-write with the same lock.
Common Mistakes & Pitfalls
- Assuming single statements are atomic: the biggest mistake — thinking
counter++is safe because it is one line, not realizing the expression is not specified as one atomic action. - Synchronizing only one side: adding
synchronizedto the getter but not the increment does not prevent interference — both need the same lock. - Thinking
volatilefixes interference:volatileensures visibility but does not make compound operations atomic —volatile intwithcount++still loses updates.
Check your understanding
Answer these without looking back at the article.
- How does the JVM prevent thread interference?
- Is array element access thread-safe?
- What bytecode does counter++ generate?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.