← Lessons

quiz vs the machine

Platinum1850

Concurrency

The Data Race Undefined Behavior

Why a single race can poison an entire C plus plus program, not just one value.

6 min read · advanced · beat Platinum to climb

More than a stale read

A data race is two conflicting accesses to the same location, at least one a write, not ordered by happens before. New programmers assume the worst case is reading a stale or torn value. In C and C plus plus the reality is harsher: a data race is undefined behavior, so the entire program has no defined meaning.

Why undefined behavior is so dangerous

Because the standard assumes races never occur, the compiler optimizes as if every program is race free. A race can then cause effects far beyond the racy variable.

  • The optimizer may assume a value cannot change and cache it, breaking unrelated logic.
  • It may delete or reorder code paths that only make sense without the race.
  • Effects can appear to time travel, corrupting state before the race in program order.

Java is different but not safe

The Java model deliberately bounds the damage: a race yields some value actually written, never an out of thin air value, preserving memory safety. But the program is still incorrect and may observe stale or inconsistent state. In both languages the cure is the same: order all conflicting accesses with atomics, volatile, or locks so no race exists.

Key idea

A data race is undefined behavior in C and C plus plus, letting the optimizer corrupt the whole program, while Java bounds the damage yet still leaves the program incorrect, so eliminate races with proper synchronization.

Check yourself

Answer to earn rating on the learn ladder.

1. What is the consequence of a data race in C plus plus?

2. How does the Java model limit data race damage?