Course contentsShow
← Java
Lesson 2645 of 2,87049. Synchronization and LockingFree lesson

Observing Race Conditions in Practice

Show how running the same multi-threaded code multiple times produces different, unpredictable results.

Observing Race Conditions in Practice

You'll learn: How to see race conditions produce unpredictable, inconsistent results when you run the same multi-threaded code multiple times.

The Unpredictability Problem

You've seen why count++ isn't atomic and understand theoretically how race conditions occur. Now let's observe them happening in real execution. The defining characteristic of race conditions is non-determinism: running identical code produces different outcomes.

Running the Counter Multiple Times

Take the simple counter example from previous lessons. If you execute it once, you might get count = 1850. Run it again immediately—same code, same machine—and you might get count = 1923. A third run: count = 2000 (correct!). A fourth: count = 1756.

This inconsistency happens because thread scheduling is unpredictable. Sometimes threads interleave in ways that cause lost updates; sometimes they happen to execute without conflict. The JVM scheduler, operating system, CPU load, and even random timing variations affect the outcome.

Why This Matters

Unlike deterministic bugs (which always fail the same way), race conditions are intermittent. They might appear once in a thousand runs, or only under heavy load. This makes them extremely difficult to debug—you can't reliably reproduce them.

The variability proves the race condition exists. If your multi-threaded counter consistently produces the wrong result differently each time, you've observed the race in action.

The Debugging Trap

Developers often add logging or debugging statements to investigate issues, which changes the timing and may make the race condition disappear temporarily—a phenomenon called a "Heisenbug."

Key Takeaway:
Race conditions manifest as inconsistent results across multiple executions of identical code—sometimes producing correct output, sometimes incorrect, with no predictable pattern. This non-determinism is the hallmark of unsynchronized shared state.