Skip to content
Tutorials Center
My learning

Topics

Lesson 103 of 134 ยท Coroutines

Shared Mutable State

Learn why shared mutable state breaks concurrent Kotlin code and how to fix it with Mutex, atomic classes, thread confinement with limitedParallelism and the actor pattern, with runnable examples.

Coroutines make it easy to start thousands of concurrent tasks. They do not make it safe for those tasks to touch the same variable. As soon as two coroutines run on different threads and one of them changes a value the other reads, you have a data race, and the program can produce wrong results without ever throwing an error.

This lesson shows a race failing in two ways, then four ways to fix it: a Mutex, atomic classes, confining the state to one thread, and the actor idea built on a channel. It follows flows and StateFlow and SharedFlow, and it uses dispatchers throughout.

Why counter++ is not one step

A line such as counter++ looks like a single action. For the computer it is three: read the current value, add one, write the result back. If two tasks interleave those steps, an update is lost.

Here is the smallest possible demonstration. It uses one thread, so the result is the same every time. Each coroutine reads the counter, then calls yield() to let the others run, then writes its value plus one.

Kotlin A lost update on one thread

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 readln()), it gets the next line from this box.

The output is expected 100, got 1. All 100 coroutines read 0 before any of them wrote, so each wrote 1. No thread was involved: a race needs only an interleaving between a read and a write, and every suspension point is a place where an interleaving can happen.

The real thing: several threads

With Dispatchers.Default the coroutines run on separate threads at the same moment, and the interleavings happen at the processor level, not only at yield().

Kotlin A data race on Dispatchers.Default

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 readln()), it gets the next line from this box.

When this page was written, one run printed expected 8000000, got 5246355. Your number will be different, and it can change on every run, because the outcome depends on thread timing. That is what makes races so nasty: the program often passes your tests and fails in production under load.

Never rely on "it printed the right number once". A data race is undefined behavior in practice: you may lose updates, read stale values, or see a half-written state of an object with several fields.

Why volatile does not save you

Kotlin has @Volatile for properties. It guarantees that a write by one thread becomes visible to other threads, but it does not make counter++ atomic. Two threads can still both read 5 and both write 6. Volatile fixes visibility; you need something else for read-modify-write sequences.

Fix 1: Mutex

A Mutex (mutual exclusion) lets one coroutine at a time into a section of code. It lives in kotlinx.coroutines.sync. The extension withLock takes the lock, runs your block and releases the lock even when the block throws.

Kotlin Protecting the counter with a Mutex

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 readln()), it gets the next line from this box.

Now it always prints expected 800000, got 800000. A Mutex is the coroutine counterpart of synchronized in Java, with one key difference: while a coroutine waits for the lock it suspends instead of blocking its thread, so the thread can run other work. That is why you must not use synchronized or ReentrantLock around code that suspends: a coroutine holding such a lock may resume on a different thread, and the thread-based lock cannot handle that. Inside a Mutex block you may call suspend functions freely.

Two traps with Mutex:

  • It is not reentrant. Taking the same mutex twice from the same coroutine deadlocks, because the second lock waits for the first to be released, and the first can only be released by the coroutine that is now waiting.
  • Locking costs time. Keep the critical section short, and never do slow work such as network calls while holding a lock unless that is the point.

Fix 2: atomic classes

For a single number, a flag or a reference, the cheapest tool is an atomic class from java.util.concurrent.atomic. AtomicInteger.incrementAndGet() performs the read-modify-write as one indivisible hardware operation, with no lock and no suspension.

Kotlin AtomicInteger and update functions

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 readln()), it gets the next line from this box.

The output is hits = 800000 and longest = wwwwwwww. updateAndGet takes a function and applies it in a retry loop (compare-and-set): if another thread changed the value in between, it computes again from the new value. For that reason the function must be pure, with no side effects, because it may run more than once.

Atomics protect one variable. They cannot keep two variables consistent with each other. If a rule says "balance and history must change together", you need a lock or one of the next two designs.

Kotlin's standard library has its own kotlin.concurrent.atomics classes for multiplatform code. On the JVM the Java classes used here are the dependable choice.

Fix 3: confine the state to one thread

The safest shared state is state that is not shared. If only one thread ever touches a variable, no race is possible. In coroutines you do this by running every access on a dispatcher that has a single thread, using limitedParallelism(1):

Kotlin Thread confinement with limitedParallelism

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 readln()), it gets the next line from this box.

It prints expected 160000, got 160000. Every increment hops to the single-parallelism view of the pool, so increments never overlap. Notice the cost: each withContext switch is more expensive than the increment itself, so this version is slow for fine-grained updates. The better pattern is coarse-grained confinement: run the whole function that owns the state on the confined dispatcher, not each tiny operation. For example, wrap a complete "process this order" step in one withContext(confined).

limitedParallelism(1) guarantees that at most one coroutine runs at a time, but not that it is always the same thread. That is enough for safety: Kotlin makes sure each switch publishes the earlier writes to the next one. If you need a literal single thread (for a library that demands it), use Executors.newSingleThreadExecutor().asCoroutineDispatcher() and close it when you are done.

Confinement is also how Android and desktop UIs work: all UI state lives on the main thread, and background work sends results back to it.

Fix 4: the actor idea

An actor owns some state and handles one message at a time from an inbox. Nobody else touches the state; they send messages. In Kotlin you can build this with one coroutine and a channel. The channel is the inbox, and the coroutine is the only code that ever reads or writes the state.

To get an answer back, a message can carry a CompletableDeferred, a promise that the actor completes. The sealed interface (see sealed classes and interfaces) describes the possible messages:

Kotlin A counter actor built on a channel

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 readln()), it gets the next line from this box.

The result is expected 400000, got 400000. The GetValue message is processed after all the increments that were sent before it, and because the inbox is in order, the reply is correct. The variable counter is a plain var, with no lock anywhere: safety comes from the design.

Older versions of kotlinx.coroutines had an actor { } builder for this. It is marked as obsolete and is no longer the recommended way, so writing the loop yourself as above is the modern approach. Actors fit best when the state is a whole object with rules (a bank account, a game room, a cache), and when you want back-pressure and ordering for free.

Choosing a tool

Situation Reach for
One counter, flag or reference AtomicInteger, AtomicReference, AtomicBoolean
Several fields that must change together, short critical section Mutex with withLock
A component with its own state and many callers confinement to one dispatcher, or an actor
A collection shared between threads ConcurrentHashMap, or a confined or locked normal map
Read-mostly data an immutable value in an AtomicReference or a StateFlow

Thread-safe Java collections protect their own internal structure, not your logic. Doing if (map[key] == null) map[key] = value on a ConcurrentHashMap is still a race between the check and the put; use computeIfAbsent or getOrPut from ConcurrentMap instead. The Java side of this story is in threads and Java concurrency.

The best fix: do not share

Most of the time you can avoid shared mutable state entirely. Let each coroutine compute a result and return it; then combine the results after await or joinAll. A parallel sum is a good example: each async returns a partial sum, and the parent adds them up on its own. Immutable data (val, List rather than MutableList, data classes with copy) can be shared freely, because nobody can change it.

Common mistakes

  • Trusting that Dispatchers.Default is single threaded. It uses several threads. Dispatchers.Main and a limitedParallelism(1) view are the single-threaded options.
  • Using synchronized around suspend calls. The compiler rejects suspension points inside synchronized, for good reason; use Mutex.
  • Locking twice with the same Mutex (not reentrant).
  • Protecting writes but not reads. A read without the lock can see a half-updated state. Use the same lock for both.
  • Making a collection thread-safe and then doing check-then-act on it.
  • Testing once. A race that fails one time in ten thousand will pass your single test run. Review the design instead.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can counter++ lose updates when two threads run it at the same time?

    Both threads can read the same old value and both write old + 1, so one increment disappears. That is a read-modify-write race.
  2. 2. What is the main advantage of Mutex over synchronized in coroutine code?

    Waiting on a Mutex suspends the coroutine, so the thread stays free. Mutex is not reentrant, so the last option is wrong.
  3. 3. Which tool is the best fit for a single shared counter?

    An atomic class makes the read-modify-write of one variable indivisible, without locks. @Volatile alone does not make counter++ atomic.
  4. 4. What does Dispatchers.Default.limitedParallelism(1) give you?

    Parallelism of one means coroutines on that view never run at the same moment, which is enough to protect state used only there.
  5. 5. In the actor pattern, who is allowed to read and write the private state?

    Other code sends messages; only the actor coroutine touches the state, one message at a time, so no lock is needed.

Summary

  • A data race happens when concurrent tasks read and write the same variable without coordination; counter++ is read, add, write, and updates can be lost.
  • Races produce different results from run to run and often pass small tests. @Volatile fixes visibility, not atomicity.
  • Mutex.withLock serializes a critical section and suspends instead of blocking; it is not reentrant.
  • Atomic classes protect one variable cheaply; updateAndGet functions must be pure.
  • Confine state to one dispatcher with limitedParallelism(1), preferably at a coarse grain, or use the actor pattern with a channel.
  • Best of all: return results instead of sharing, and prefer immutable data.

Next: Testing Coroutines