Why does volatile not make counter++ thread-safe, and what would you use instead?
Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Saved automatically
Model Answer & Deep-Dive Explanation
volatile provides visibility and ordering guarantees for accesses to the field, but increment is a read-modify-write sequence. Two threads can read the same value and both write the same incremented result, losing an update. AtomicInteger.incrementAndGet provides an atomic increment; synchronized or a lock can protect a larger invariant involving several fields. Pick the mechanism according to what must change together. An atomic counter does not automatically make associated collection updates atomic or make every operation in the surrounding method thread-safe.
Related Questions in Java
Advanced Java Interview Questions and Answers
Advanced level • 841 views
Java Web development interview questions
Advanced level • 663 views
Java Interview questions
Advanced level • 629 views
Java questions for Newbies
Intermediate level • 573 views
Interview questions on EJB
Advanced level • 454 views