Race conditions
suggest changeA race condition happens when the result of a program depends on the timing of two or more concurrent operations that touch the same data. The code looks correct, passes tests most of the time, and then produces a wrong total, a negative balance or a corrupted collection under load.
Kotlin on the JVM can run code concurrently with plain threads and with Coroutines. Both can race, and coroutines add one twist: they can race even on a single thread, because every suspension point is a place where another coroutine can run.
This article covers:
- the classic lost update (
counter++) with threads and coroutines - fixing it with atomics, locks,
Mutex, thread confinement and message passing - check-then-act races and why thread-safe collections don't save you
- races between coroutines on a single thread
- visibility problems and
@Volatile - safe updates of immutable state with
AtomicReferenceandMutableStateFlow - avoiding shared mutable state altogether
- how to test for races
The coroutine examples use this dependency:
// build.gradle.kts
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
}
The lost update
Four threads each increment a shared counter 100,000 times. You'd expect 400,000:
import kotlin.concurrent.thread
fun main() {
var counter = 0
val threads = List(4) {
thread {
repeat(100_000) { counter++ }
}
}
threads.forEach { it.join() }
println("counter = $counter")
}
Example output (it differs on every run):
counter = 172934
counter++ is not one operation. It is three: read the current value, add 1, write the new value back. When two threads interleave like this, one increment is lost:
thread A: read counter (5)
thread B: read counter (5)
thread A: write 5 + 1 (6)
thread B: write 5 + 1 (6) <- A's increment is gone
The same thing happens with coroutines running on a multi-threaded dispatcher such as Dispatchers.Default:
import kotlinx.coroutines.*
suspend fun massiveRun(action: suspend () -> Unit) {
coroutineScope {
repeat(100) { // 100 coroutines
launch {
repeat(1000) { action() } // each does the action 1000 times
}
}
}
}
var counter = 0
fun main() = runBlocking {
withContext(Dispatchers.Default) {
massiveRun { counter++ }
}
println("counter = $counter")
}
Example output:
counter = 61873
Coroutines are not magic: if they run in parallel on several threads and share a mutable variable, they need the same protection as threads. We'll reuse massiveRun in the following sections.
Fix 1: atomic variables
For a single counter or flag, the simplest and fastest fix is an atomic class from java.util.concurrent.atomic. Its operations are performed as one indivisible step using CPU compare-and-swap instructions, without locks:
import kotlinx.coroutines.*
import java.util.concurrent.atomic.AtomicInteger
val counter = AtomicInteger(0)
fun main() = runBlocking {
withContext(Dispatchers.Default) {
massiveRun { counter.incrementAndGet() }
}
println("counter = ${counter.get()}")
}
counter = 100000
Useful atomic classes and methods:
| Class | Common methods |
|---|---|
AtomicInteger, AtomicLong |
get, set, incrementAndGet, addAndGet, getAndIncrement, compareAndSet, updateAndGet { } |
AtomicBoolean |
get, set, compareAndSet, getAndSet |
AtomicReference<T> |
get, set, compareAndSet, updateAndGet { }, getAndUpdate { } |
LongAdder |
increment, add, sum |
When many threads update a counter constantly (request statistics, metrics) and you read it rarely, LongAdder scales better than AtomicLong because it spreads updates across internal cells:
import java.util.concurrent.atomic.LongAdder
import kotlin.concurrent.thread
fun main() {
val requests = LongAdder()
val threads = List(8) { thread { repeat(1_000_000) { requests.increment() } } }
threads.forEach { it.join() }
println("requests = ${requests.sum()}")
}
requests = 8000000
Kotlin 2.1.20+ also has multiplatform atomics in kotlin.concurrent.atomics (AtomicInt, AtomicLong, AtomicBoolean, AtomicReference). They are still experimental, so they need an opt-in:
import kotlin.concurrent.atomics.AtomicInt
import kotlin.concurrent.atomics.ExperimentalAtomicApi
@OptIn(ExperimentalAtomicApi::class)
val hits = AtomicInt(0)
@OptIn(ExperimentalAtomicApi::class)
fun recordHit() {
hits.addAndFetch(1)
}
@OptIn(ExperimentalAtomicApi::class)
fun totalHits(): Int = hits.load()
On the JVM they compile down to the same java.util.concurrent.atomic machinery. Use them in multiplatform code; in JVM-only code the Java classes are fine.
An atomic protects one variable. If an invariant spans two variables (for example balance and transactionCount must change together), atomics on each of them are not enough. You need a lock.
Fix 2: locks
A lock makes a block of code a critical section: only one thread can execute it at a time. Kotlin's stdlib has synchronized(lock) { } for JVM monitors:
import kotlin.concurrent.thread
class Account(private var balance: Long) {
private val lock = Any()
private var transactions = 0
fun deposit(amount: Long) {
synchronized(lock) {
balance += amount
transactions++
}
}
fun snapshot(): Pair<Long, Int> = synchronized(lock) { balance to transactions }
}
fun main() {
val account = Account(0)
val threads = List(4) { thread { repeat(10_000) { account.deposit(5) } } }
threads.forEach { it.join() }
println(account.snapshot())
}
(200000, 40000)
Notice that snapshot() is synchronized too. Reading without the lock could see balance updated but transactions not yet updated, and on the JVM an unsynchronized read isn't even guaranteed to see the latest value at all.
You can also mark a whole method with @Synchronized, which locks on this (like Java's synchronized method modifier):
class Counter {
private var value = 0
@Synchronized
fun increment() { value++ }
@Synchronized
fun get(): Int = value
}
A dedicated private lock object is usually better than @Synchronized, because outside code can't accidentally lock on it.
For more control (try-lock, timeouts, read/write locks) use java.util.concurrent.locks with Kotlin's withLock extension, which always unlocks in a finally:
import java.util.concurrent.locks.ReentrantReadWriteLock
import kotlin.concurrent.read
import kotlin.concurrent.write
class Config {
private val rw = ReentrantReadWriteLock()
private val values = mutableMapOf<String, String>()
fun get(key: String): String? = rw.read { values[key] } // many readers at once
fun set(key: String, value: String) = rw.write { values[key] = value } // exclusive
}
ReentrantLock().withLock { ... } works the same way for a plain exclusive lock.
Fix 3: Mutex for coroutines
JVM locks block the thread. Inside coroutines you can't suspend while holding one: the compiler rejects this code with an error like "The 'delay' suspension point is inside a critical section":
synchronized(lock) {
delay(100) // compile error
}
The coroutine equivalent is Mutex from kotlinx.coroutines.sync. Waiting for it suspends the coroutine instead of blocking a thread, and the body of withLock may call suspending functions:
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
val mutex = Mutex()
var counter = 0
fun main() = runBlocking {
withContext(Dispatchers.Default) {
massiveRun {
mutex.withLock { counter++ }
}
}
println("counter = $counter")
}
counter = 100000
Things to know about Mutex:
- It is not reentrant. Calling
withLockon the same mutex from insidewithLockdeadlocks. - Keep critical sections short. A mutex around a slow network call serializes all callers.
- For a plain counter, an
AtomicIntegeris much faster. UseMutexwhen the critical section contains suspending calls or updates several values together. Semaphore(permits)from the same package is the generalization: it lets up topermitscoroutines in at once, which is handy for limiting concurrent requests.
Fix 4: confine state to one thread
Instead of protecting state, make sure only one thread ever touches it. limitedParallelism(1) creates a view of a dispatcher that runs at most one coroutine at a time:
import kotlinx.coroutines.*
val counterDispatcher = Dispatchers.Default.limitedParallelism(1)
var counter = 0
fun main() = runBlocking {
withContext(counterDispatcher) {
massiveRun { counter++ }
}
println("counter = $counter")
}
counter = 100000
Here all of massiveRun is confined (coarse-grained confinement), which is fast. Switching to the confined dispatcher for each increment (withContext(counterDispatcher) { counter++ } inside the action) is also correct but much slower, because each call is a context switch.
This is exactly how UI frameworks work: Android and desktop UI state may only be touched on the main thread, and Dispatchers.Main is the confining dispatcher.
Fix 5: message passing
Another way to confine state is to give it to one coroutine and let others talk to it through a Channel. No one else can see the variable, so there's nothing to race on:
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
sealed interface CounterMsg
data object Increment : CounterMsg
class GetValue(val reply: CompletableDeferred<Int>) : CounterMsg
fun CoroutineScope.counterActor(): SendChannel<CounterMsg> {
val inbox = Channel<CounterMsg>(capacity = Channel.UNLIMITED)
launch {
var counter = 0 // private to this coroutine
for (msg in inbox) {
when (msg) {
Increment -> counter++
is GetValue -> msg.reply.complete(counter)
}
}
}
return inbox
}
fun main() = runBlocking<Unit> {
val counter = counterActor()
withContext(Dispatchers.Default) {
massiveRun { counter.send(Increment) }
}
val reply = CompletableDeferred<Int>()
counter.send(GetValue(reply))
println("counter = ${reply.await()}")
counter.close() // lets the actor's loop finish
}
counter = 100000
Messages are processed one at a time in the order they were sent, so the GetValue request sees all increments sent before it. This pattern (often called an actor) shines when the state is complex and has several operations, for example a connection pool or an in-memory game state.
Check-then-act races
Lost updates are one kind of race. The other common kind is check-then-act: you check a condition, then act on it, but the condition may no longer hold by the time you act.
A thread-safe collection makes each individual call safe, but not a sequence of calls:
import java.util.concurrent.ConcurrentHashMap
val counts = ConcurrentHashMap<String, Int>()
// WRONG: get and put are each atomic, but two threads can both read 3
// and both write 4
fun recordBad(word: String) {
counts[word] = (counts[word] ?: 0) + 1
}
// WRONG: two threads can both see "missing" and both create a session
fun sessionBad(user: String, sessions: ConcurrentHashMap<String, Session>): Session {
if (!sessions.containsKey(user)) {
sessions[user] = Session(user)
}
return sessions.getValue(user)
}
class Session(val user: String)
Use the map's atomic compound operations instead:
import java.util.concurrent.ConcurrentHashMap
import kotlin.concurrent.thread
fun main() {
val counts = ConcurrentHashMap<String, Int>()
val words = listOf("red", "green", "red", "blue", "red", "green")
val threads = List(4) {
thread {
repeat(1000) {
for (w in words) counts.merge(w, 1, Int::plus)
}
}
}
threads.forEach { it.join() }
println(counts.toSortedMap())
val sessions = ConcurrentHashMap<String, String>()
val s = sessions.computeIfAbsent("alice") { user -> "session-of-$user" }
println(s)
}
{blue=4000, green=8000, red=12000}
session-of-alice
Atomic operations on ConcurrentHashMap:
merge(key, value) { old, new -> ... }: combine with the existing value, or insertcompute(key) { k, old -> ... }: replace the value based on the old one (returnnullto remove)computeIfAbsent(key) { ... }: create a value only if missing; the lambda runs at most once per keyputIfAbsent(key, value),replace(key, old, new),remove(key, value)
Beware of Kotlin's getOrPut on a ConcurrentMap: it only stores one value, but its lambda can run several times under contention. See Caching for more.
Races on a single thread
With threads, a race needs parallelism. With coroutines it doesn't. runBlocking runs all its coroutines on one thread, yet this bank account goes negative every time:
import kotlinx.coroutines.*
var balance = 100
suspend fun withdraw(amount: Int): Boolean {
if (balance >= amount) {
delay(10) // e.g. ask a fraud-check service
balance -= amount
return true
}
return false
}
fun main() = runBlocking {
val results = List(3) { async { withdraw(60) } }.awaitAll()
println("results = $results")
println("balance = $balance")
}
results = [true, true, true]
balance = -80
Each coroutine checks the balance (100 is enough for 60), then suspends in delay. While it is suspended the next coroutine runs and passes the same check. The check and the update are separated by a suspension point, so they are not atomic.
The rule: assume anything can change across a suspension point. Either re-read state after suspending, or hold a Mutex across the whole check-and-update:
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
var balance = 100
val accountMutex = Mutex()
suspend fun withdraw(amount: Int): Boolean = accountMutex.withLock {
if (balance >= amount) {
delay(10)
balance -= amount
true
} else {
false
}
}
fun main() = runBlocking {
val results = List(3) { async { withdraw(60) } }.awaitAll()
println("results = $results")
println("balance = $balance")
}
results = [true, false, false]
balance = 40
Often the better design is to do the slow, suspending work outside the lock and keep only the fast check-and-update inside it, re-validating the condition there.
Visibility and @Volatile
Races aren't only about interleaving. The JVM and the CPU may cache values and reorder writes, so without synchronization one thread may never see a write made by another. A classic example is a stop flag:
import kotlin.concurrent.thread
class Worker {
@Volatile
private var running = true
var iterations = 0L
private set
fun run() {
while (running) {
iterations++
}
}
fun stop() {
running = false
}
}
fun main() {
val worker = Worker()
val t = thread { worker.run() }
Thread.sleep(100)
worker.stop()
t.join() // without @Volatile this may hang forever
println("stopped after some iterations: ${worker.iterations > 0}")
}
stopped after some iterations: true
Without @Volatile, the JIT compiler is allowed to read running once, see true, and turn the loop into an infinite one. @Volatile guarantees that every read sees the most recent write.
@Volatile gives visibility, not atomicity. @Volatile var counter = 0 with counter++ from several threads still loses updates. Use it for flags and for publishing a reference written by one thread and read by others; use atomics or locks for read-modify-write.
Everything done inside synchronized, Mutex.withLock, atomic operations, Thread.join(), and coroutine join()/await() also establishes visibility, which is why the earlier examples could safely read the results after waiting for the workers.
Updating immutable state atomically
A clean way to share complex state is to keep it in an immutable data class and replace the whole object atomically. AtomicReference.updateAndGet retries the lambda until its compare-and-swap succeeds:
import java.util.concurrent.atomic.AtomicReference
import kotlin.concurrent.thread
data class Stats(val requests: Int = 0, val errors: Int = 0)
fun main() {
val stats = AtomicReference(Stats())
val threads = List(4) { n ->
thread {
repeat(1000) { i ->
val failed = (i + n) % 10 == 0
stats.updateAndGet { s ->
s.copy(
requests = s.requests + 1,
errors = if (failed) s.errors + 1 else s.errors,
)
}
}
}
}
threads.forEach { it.join() }
println(stats.get())
}
Stats(requests=4000, errors=400)
Because the lambda may run more than once, it must be a pure function: no I/O, no logging, no incrementing other counters inside it.
In coroutine code the same idea is built into MutableStateFlow.update:
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
data class Cart(val items: List<String> = emptyList())
fun main() = runBlocking {
val cart = MutableStateFlow(Cart())
withContext(Dispatchers.Default) {
repeat(100) { i ->
launch { cart.update { it.copy(items = it.items + "item-$i") } }
}
}
println(cart.value.items.size)
}
100
Writing cart.value = cart.value.copy(...) instead would be a read-modify-write race and could lose items. Always use update { } (or getAndUpdate / updateAndGet) when the new value depends on the old one.
Shared collections
Standard collections (mutableListOf, mutableMapOf, HashMap, ArrayList) are not thread-safe. Adding from several threads doesn't just lose elements; it can corrupt the internal array and throw:
import kotlinx.coroutines.*
fun main() = runBlocking {
val results = mutableListOf<Int>()
withContext(Dispatchers.Default) {
repeat(10_000) { i -> launch { results.add(i * i) } }
}
println(results.size)
}
Example output (or an ArrayIndexOutOfBoundsException):
9971
Thread-safe options from java.util.concurrent:
ConcurrentHashMapinstead ofHashMapConcurrentLinkedQueueorLinkedBlockingQueuefor queuesCopyOnWriteArrayListfor lists that are read very often and modified rarely (listeners)Collections.synchronizedList(mutableListOf())as a simple fallback; iterating it still needssynchronized(list) { }
But the best fix is usually to not share the collection at all. Let each coroutine return its result and gather them in one place:
import kotlinx.coroutines.*
fun main() = runBlocking {
val results = withContext(Dispatchers.Default) {
(0 until 10_000).map { i -> async { i * i } }.awaitAll()
}
println(results.size)
println(results.take(5))
}
10000
[0, 1, 4, 9, 16]
No shared mutable state, no locks, and the results are in order.
Lazy initialization
Hand-written lazy initialization is a check-then-act race:
object Registry {
private var instance: ExpensiveClient? = null
// WRONG: two threads can both see null and create two clients
fun client(): ExpensiveClient {
if (instance == null) instance = ExpensiveClient()
return instance!!
}
}
class ExpensiveClient
Use by lazy, which is synchronized by default and runs the initializer exactly once:
object Registry {
val client: ExpensiveClient by lazy { ExpensiveClient() }
}
Kotlin object declarations are themselves initialized thread-safely by the JVM class loader, so a singleton object needs no extra locking for its own construction.
Testing for races
Races are timing dependent, so a single test run proves little. Some practical techniques:
- Stress tests: run the operation from many threads or coroutines, many times, and check an invariant at the end (the total, the size, no exceptions).
- Start everything at once with a
CountDownLatchor aCompletableDeferredgate, so workers actually overlap instead of finishing one after another. - Run on a multi-core machine with
Dispatchers.Default, not insiderunTestorrunBlocking, which use a single thread and hide thread races (they still reveal suspension-point races like thewithdrawexample). - Lincheck (
org.jetbrains.kotlinx:lincheck) systematically explores interleavings of operations on a concurrent data structure and reports a minimal failing scenario.
A simple stress-test helper:
import java.util.concurrent.CountDownLatch
import kotlin.concurrent.thread
fun stress(threads: Int, iterations: Int, action: () -> Unit) {
val start = CountDownLatch(1)
val workers = List(threads) {
thread {
start.await() // all threads begin at the same moment
repeat(iterations) { action() }
}
}
start.countDown()
workers.forEach { it.join() }
}
class UnsafeCounter { var value = 0; fun inc() { value++ } }
fun main() {
repeat(5) { round ->
val c = UnsafeCounter()
stress(threads = 8, iterations = 10_000) { c.inc() }
println("round $round: ${c.value} (expected 80000)")
}
}
Example output:
round 0: 41327 (expected 80000)
round 1: 52004 (expected 80000)
round 2: 38811 (expected 80000)
round 3: 47290 (expected 80000)
round 4: 44102 (expected 80000)
Choosing a fix
| Situation | Use |
|---|---|
| single counter, flag or reference | AtomicInteger / AtomicLong / AtomicBoolean / AtomicReference |
| hot counter updated by many threads | LongAdder |
| several values that must change together, blocking code | synchronized or ReentrantLock.withLock |
| critical section in coroutines, may suspend | Mutex.withLock |
| state owned by one component | confinement: limitedParallelism(1), Dispatchers.Main, or an actor with a Channel |
| observable state in coroutine code | immutable data class in MutableStateFlow + update { } |
| map shared between threads | ConcurrentHashMap with merge / compute / computeIfAbsent |
| results of parallel work | return values from async and awaitAll() instead of a shared list |
| stop flag read in a loop | @Volatile |
Gotchas
count++is never atomic, not withvar, not with@Volatile. Use an atomic class.- A thread-safe collection doesn't make sequences of calls atomic.
if (!map.containsKey(k)) map[k] = vraces even on aConcurrentHashMap. - Coroutines race on one thread. State read before a suspension point may be stale after it.
- Don't block in coroutines. Use
Mutexinstead ofsynchronizedaround suspending code; the compiler forbids suspension insidesynchronizedanyway. Mutexis not reentrant. NestedwithLockon the same mutex deadlocks.- Lambdas passed to
updateAndGetandMutableStateFlow.updatemay run several times. Keep them free of side effects. - Reads need protection too. Reading shared state without the lock (or
@Volatile/ atomics) can return stale or half-updated values. - Lock ordering matters. If code locks
athenbin one place andbthenain another, two threads can deadlock. Always acquire multiple locks in the same order, or avoid holding more than one.