What is a race condition? Can you give an example?
A race condition happens when the correctness of a program's outcome depends on the unpredictable timing or interleaving of multiple threads. A classic example is the expression count++, which is not atomic even though it looks like a single operation: it actually compiles down to three steps -- read the current value, add one, and write the result back. If two threads both read count as 5 at the same time, both compute 6, and both write 6 back, the final value is 6 even though two increments happened and the expected result was 7 -- one update is silently lost. This is fixed by making the operation atomic, for example by wrapping it in a synchronized block, using AtomicInteger's incrementAndGet() method, or using LongAdder for high-throughput counters.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response