Java Reference ยท Concurrency
Race conditions in Java
What a race condition is in Java, why count++ is not atomic, check-then-act bugs, how to detect races and the tools that fix them: locks, atomics and immutability.
A race condition is a bug whose outcome depends on the timing of threads. The most common kind is a data race: two threads access the same variable at the same time, at least one of them writes, and there is no synchronization between the accesses. Java gives no guarantees for such code: you may lose updates, read stale values or see objects half-constructed.
Race conditions are hard because the program is usually correct most of the time. The bug appears under load, on another CPU count, or in production on a Friday. This page is a concept page: it shows what the common races look like, how to make a race visible without relying on luck, and which tools remove it.
Two shapes cover most cases. A read-modify-write race (count++) loses updates because the read, the add and the write are separate steps. A check-then-act race (if (!map.containsKey(k)) map.put(k, v)) acts on a condition that another thread may have changed in between.
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Fixing and finding races
| Technique | When to use it |
|---|---|
synchronized / Lock |
Protect compound updates of several fields; all accesses must use the same lock. |
AtomicInteger, LongAdder, AtomicReference |
A single variable with read-modify-write operations. |
volatile |
Visibility of a simple flag; it does not make count++ atomic. |
ConcurrentHashMap.computeIfAbsent, merge |
Atomic check-then-act on a map. |
Immutable objects, records |
Share data safely by never changing it. |
Confinement (ThreadLocal, one owning thread) |
Avoid sharing at all. |
Message passing (BlockingQueue) |
Hand ownership of an object from one thread to another. |
To find races: stress tests with many threads released by a latch, repeated thousands of times; the jcstress harness for memory-model questions; ThreadSanitizer-style tools for native code; and code review that asks, for every shared field, "which lock protects this?" Document the answer with a comment or an annotation like @GuardedBy.
Usage notes
- A test that passes is not proof. Races depend on timing; one CPU hides many of them, because threads rarely interleave in the middle of a short statement.
volatileis not enough for read-modify-write. Use an atomic or a lock.- Safe publication: an object shared through a plain field can be seen half-initialized. Publish through a
volatilefield, afinalfield, a lock or a concurrent collection. - Thread-safe parts do not make a thread-safe whole. Two atomic fields or two synchronized calls in a row can still be an invariant violation between the calls.
- Double-checked locking works only with a
volatilefield (or a holder class that uses class initialization). - Never print unstable values in tests. Assert on properties that must hold (the total, the sorted contents) instead.
HashMapandArrayListare not thread-safe; concurrent writes can lose entries or, in rare cases, corrupt the structure.- Races are not only about memory: two processes creating the same file, or checking and then writing a file, have the same time-of-check/time-of-use shape.