Java › Concurrency & Threads
What is a race condition, and how does it differ conceptually from a deadlock as two distinct categories of concurrency bugs?
IntermediateAnswer
A race condition occurs when the correctness of a program's outcome depends on the unpredictable relative timing/interleaving of multiple threads accessing shared mutable state without adequate synchronization, producing incorrect results (like lost updates) that may vary nondeterministically between runs; a deadlock, by contrast, is a liveness failure where threads become permanently stuck waiting for each other in a circular dependency, producing no forward progress at all rather than an incorrect result -- a race condition corrupts correctness silently, while a deadlock halts execution entirely and visibly (typically detectable via a thread dump showing threads stuck in BLOCKED state).
// Race condition example: unsynchronized shared counter increment
int[] counter = {0};
Runnable increment = () -> counter[0]++; // read-modify-write, not atomic
// Running this concurrently from multiple threads produces an unpredictable, often INCORRECT final count
// Deadlock example: two threads waiting on each other's locks (see lock ordering question for full example)
// Produces NO progress at all, rather than a wrong-but-completed resultReal-world example A load test reveals a payment processing counter occasionally undercounts transactions under concurrent load (a race condition producing a silently wrong number), which is a fundamentally different class of bug from a separate incident where the same system occasionally hung entirely and stopped processing any transactions (a deadlock), requiring different diagnostic and fix approaches for each.