Java Concurrency Interview

The Java memory model question 23 of 180 senior

What is the difference between a data race and a race condition?

A data race is a memory model term with a precise definition: two accesses to the same variable from different threads, at least one of them a write, not ordered by happens-before. A race condition is a correctness term: the outcome of the program depends on the relative timing of its threads.

Neither implies the other, and an example of each is what the interviewer is waiting for.

A race condition with no data race: check-then-act on a thread-safe class. Every access goes through a ConcurrentHashMap, so nothing is unordered, and two threads can still both see the key missing.

if (!map.containsKey(key)) {   // a ConcurrentHashMap: no data race anywhere
    map.put(key, value);       // and still a race condition
}

A data race with no race condition: String.hashCode() caches the hash in a plain, non-volatile int field. Two threads may compute it at once and write it unsynchronised, which is a data race, but they always write the same value and an int cannot tear, so the result is always right. It is the textbook benign race, and it is only benign because String is immutable.

Why the distinction matters: being free of data races is what the memory model rewards with sequential consistency, and fixing a data race with volatile does nothing for a race condition. The check-then-act above needs putIfAbsent or computeIfAbsent, not a stronger field.

memory-model race-condition theory

Quiz yourself on The Java memory model Suggest a correction