Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
Define a race condition in multithreading?
A race condition occurs when two or more threads access shared mutable state concurrently, and the final outcome depends on the unpredictable timing or interleaving of their operations, rather than being deterministic.
class Counter { int value = 0; void increment() { value++; } // read, add 1, write - three separate steps }
If two threads call increment() at the same time on the same Counter, both might read the same starting value before either writes back the incremented result, so one increment gets silently lost.
Race conditions are fixed by making the shared operation atomic or mutually exclusive, using synchronized, an explicit Lock, or an atomic class such as AtomicInteger, so the read-modify-write sequence can't be interrupted by another thread.
More Related questions...