volatile vs AtomicInteger Use Cases
Fast recall
Quick revision
Core answer
volatile when a protocol needs visibility and ordering for plain reads and writes, such as publishing a stop flag; it can have one or several writers if plain last-write-wins semantics are acceptable. Use AtomicInteger when you need atomic operations such as increment or compare-and-set on one integer. Use a lock for invariants across several values.Practical decision-making — choosing the right concurrency tool for the use case
Using volatile for a counter and wondering why the count doesn't reach the expected value under load
Give the exact rule: single writer scenario use volatile; multiple writers doing compound operations use AtomicInteger
Interview-ready guide
Interview answer
I use volatile when assigning and reading one field is the complete communication protocol. For example, publishing volatile boolean stopping = true can make a worker observe a stop request, although blocked work may also need interruption. Several writers are still legal when last-write-wins is the intended behavior.
I use AtomicInteger when one integer needs a compound atomic operation. For example, several request tasks can call incrementAndGet() without the lost update possible with volatile int count; count++. Methods such as compareAndSet also support conditional updates to that one value. If the rule spans a count plus other fields, neither primitive creates a transaction across them; I use a lock or publish one immutable state object. I choose this from semantics and measure performance separately.
volatile vs AtomicInteger Use Cases
Direct Answer
Use volatile when a protocol needs visibility and ordering for plain reads and writes, such as publishing a stop flag; it can have one or several writers if plain last-write-wins semantics are acceptable. Use AtomicInteger when you need atomic operations such as increment or compare-and-set on one integer. Use a lock for invariants across several values.
Common Mistakes & Pitfalls
- Making a counter volatile:
count++remains a compound race. - Treating one writer as the definition of volatile: the correct question is whether a plain assignment is the complete transition.
- Assuming AtomicInteger protects other fields: its atomicity covers its own documented operation only.
- Claiming every atomic method is one hardware instruction: Java specifies behavior, while implementation depends on the platform and JVM.
- Promising a universal speedup over a lock: contention and the size of the invariant decide actual performance.
Check your understanding
Answer these without looking back at the article.
- Can volatile be used for a double-checked locking singleton?
- What are other classes in java.util.concurrent.atomic?
- Is volatile sufficient for a published immutable object reference?
Looking for a structured roadmap?
Every module on this page is also part of the full Java backend interview track.