1. Why do coroutines need Mutex?
When you write sequential code, var balance = 100 looks harmless: just a number. But in a concurrent world, a variable suddenly gets a “social life”: different coroutines start coming up to it and changing it “right now” — and you no longer control the order in which it happens. The problem is not that Kotlin is “bad” or coroutines are “unfair”, but that multiple independent executors are touching the same data without rules.
In the Kotlin documentation on coroutines, this idea is phrased like this: when multiple coroutines access the same mutable state, without coordination you can get a race condition — unpredictable interference between operations.
To bring rules back into the game, we need a mechanism like “only one person in the room with the state at a time”. In coroutines, that mechanism is often Mutex.
Critical section and invariants
The phrase “critical section” sounds like a survival lecture for the apocalypse. In practice it is simpler: a critical section is the minimal piece of code that must run as one unit, without other coroutines “cutting in” between steps.
The most common beginner trap is thinking that we are protecting “the variable balance”. In reality, we protect an integrity rule, i.e., an invariant. For example: “the balance must not go negative”, “a withdrawal must be a check-then-act as one atomic action”, “the expense list must not break under parallel adds”.
Once you can say the invariant out loud, the boundaries of the critical section start to define themselves almost automatically: the critical section includes exactly the piece of logic you cannot split apart.
2. Mutex and withLock: setup and the basic template
How to wire it up and how to think about Mutex
Mutex in coroutines is not a “heavy lock” from the thread world, but a cooperative synchronization primitive for suspend code. It allows a coroutine to “wait” without blocking a thread (i.e., without occupying the precious resource of a “real” thread).
In practice you almost always need two imports:
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
Then you create Mutex() like a regular object:
val mutex = Mutex()
It is important to agree with yourself on style right away: Mutex should almost never be “scattered across the project” as a global magic thing. Usually it belongs to a specific object/service that owns the state. Then you get a clear contract: “if you want to touch the state, do it through this service’s methods, and the service will synchronize access itself”.
Why withLock { ... } is the main template
When locking begins, beginners get a natural urge: “I’ll do everything manually, like an adult”. At that moment, a bug smiles somewhere, because “manually” you will almost certainly forget some unlock() on an if branch, on an exception, or on an early return.
withLock { ... } solves this problem in a simple way: you give it a lambda, the library “enters” the lock and reliably “exits” it after the block finishes. Even if an exception happens inside, you will not leave the lock stuck in the “held forever” state.
Visually it looks like this:
flowchart TD
A[Coroutine wants to change state] --> B["mutex.withLock { ... }"]
B --> C[Acquire Mutex]
C --> D[Critical section]
D --> E[Release Mutex]
E --> F[Coroutine continues work]
Now you can focus on the main thing: where the critical-section boundaries are, not “did I forget to unlock”.
4. Critical-section boundaries: how not to turn Mutex into a “traffic jam”
It is very tempting to write: “take the lock — and do everything inside, so it is definitely safe”. It works, but it often turns the program into one long queue: all coroutines stand and wait while one coroutine finishes a huge chunk of work.
The rule is simple: hold Mutex only for the lines that actually protect the invariant. Everything you can do before locking or after unlocking — do before or after. Be especially careful with long operations: delay(), file reads, network requests, heavy computations. Even if delay() does not block the thread, you still hold the lock and prevent other coroutines from updating the state, which is lost throughput.
Compare two approaches “at a glance”:
| Approach | What happens | Result |
|---|---|---|
| “Large” critical section | Mutex is held for a long time; others wait | Safe, but slow and stressful |
| “Minimal” critical section | Mutex is held only while updating state | Safe and noticeably snappier |
5. Examples: a counter and check-then-act
Protecting counter++ with Mutex.withLock
A counter is a classic example. It is simple but very illustrative: counter++ looks like one operation, but in reality it is “read → add → write”. If another coroutine interferes between these steps, you lose increments.
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
fun main() = runBlocking {
var counter = 0
val mutex = Mutex()
val jobs = List(1_000) {
launch(Dispatchers.Default) {
mutex.withLock {
counter++
}
}
}
jobs.forEach { it.join() }
println("counter=$counter") // counter=1000
}
The key idea here is not that “we got 1000”. The key idea is that we clearly identified the critical section: exactly one line that updates state. Everything else runs in parallel.
check-then-act and the invariant “the balance must not go negative”
A counter is a warm-up. The real pain starts where logic consists of multiple steps that must stay together. A typical race pattern is check-then-act: “check a condition → perform an action”. If these two steps are not protected as a single block, two coroutines can pass the check “almost simultaneously” and then both perform the action — and the invariant breaks.
Suppose we have a balance, and we want to withdraw money only if there is enough:
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
suspend fun withdraw(
mutex: Mutex,
amount: Int,
get: () -> Int,
set: (Int) -> Unit
): Boolean {
return mutex.withLock {
val balance = get()
if (balance >= amount) {
set(balance - amount)
true
} else {
false
}
}
}
Note the meaning: we are not doing two separate operations “check” and “withdraw”. We are doing one critical section where checking and withdrawing live together. That is the invariant protection.
And yes, the withdraw function here is suspend. This is not “just for beauty”, but a fundamental contract: since there is withLock inside, and it can suspend the coroutine while waiting, our helper must also be suspend.
6. Helper-function design: suspend instead of runBlocking
This is where people with good intentions create an evil boss for their future selves.
Sometimes you want to write a helper so it can be called from anywhere, even from regular non-coroutine code. And then a “brilliant” idea appears: “I’ll just put runBlocking inside the helper, and that’s it!”. It looks convenient… until you hit weird slowdowns, hangs, or until your “non-blocking” code suddenly starts blocking threads.
Anti-pattern: runBlocking inside a helper
A bad example typically looks like this:
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
fun incrementWrong(mutex: Mutex, box: IntArray) {
runBlocking {
mutex.withLock {
box[0]++
}
}
}
Technically it “works”, but in meaning you just made a synchronous thread-blocking call just to pretend that everything is coroutine-based. The caller expected a normal function but got hidden waiting, hidden blocking, and very tricky performance problems. It is roughly like “I just wanted tea”, and you were brought a kettle, a stove, and a gas bill.
The correct variant: an honest suspend helper
A good variant is an honest suspend helper:
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
suspend fun incrementRight(mutex: Mutex, box: IntArray) {
mutex.withLock {
box[0]++
}
}
Now the contract is transparent: if you want to call incrementRight, please do so from a coroutine (or from another suspend function). No hidden blocking, no surprises.
7. Practical example: a thread-safe ExpenseLedger
So this does not remain “an example about a balance”, let us work through a practical example: a console expense tracker. Earlier we stored expenses in collections, added commands and reports. Now imagine we import expenses in parallel from multiple sources (for example, “bank A” and “bank B”), and both imports write into one shared ledger.
Let us make a small model and storage. Let us immediately agree on the correct contract: access to state (the expense list) goes only through ExpenseLedger methods, and ExpenseLedger protects invariants internally.
data class Expense(
val id: String,
val amount: Int,
val category: String
)
A minimal critical section in add
Now the ledger itself with Mutex:
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
class ExpenseLedger {
private val mutex = Mutex()
private val items = mutableListOf<Expense>()
suspend fun add(expense: Expense) = mutex.withLock {
items.add(expense)
}
}
Notice how “small” the critical section is: we do not do formatting, printing, sorting, or reports there. We do one thing: mutate the internal list.
snapshot() instead of exposing a mutable list
Now you often also want to read the data. And here a subtle moment appears: if you return items, you hand out a reference to your internal mutable list. It is almost like giving your neighbors the keys to your fridge and then being surprised that the dumplings disappear.
So it is better to return a snapshot (a copy of the list), also under Mutex:
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
class ExpenseLedger {
private val mutex = Mutex()
private val items = mutableListOf<Expense>()
suspend fun add(expense: Expense) = mutex.withLock {
items.add(expense)
}
suspend fun snapshot(): List<Expense> = mutex.withLock {
items.toList()
}
}
snapshot() returns an externally immutable List<Expense> (a read-only interface), and internally a new collection. This protects your invariant: “the expense ledger changes only through my methods”.
8. Parallel import: multiple coroutines add expenses into one ledger
Now let us assemble a small scenario: two coroutines “import” expenses (we simulate import with simple data), and at the end we print how many we got.
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val ledger = ExpenseLedger()
val j1 = launch(Dispatchers.Default) {
ledger.add(Expense(id = "a1", amount = 100, category = "food"))
ledger.add(Expense(id = "a2", amount = 250, category = "transport"))
}
val j2 = launch(Dispatchers.Default) {
ledger.add(Expense(id = "b1", amount = 400, category = "food"))
ledger.add(Expense(id = "b2", amount = 90, category = "coffee"))
}
joinAll(j1, j2)
val all = ledger.snapshot()
println("total items=${all.size}") // total items=4
}
If ExpenseLedger did not protect the list, you could catch “rare” and unpleasant problems, especially if in addition to add there were operations like “check uniqueness of id and then add” (that same check-then-act).
9. Where to place withLock: inside the method or outside
Sometimes a question comes up: “Can I just take mutex.withLock myself in main and do operations under it?” You can, but it almost always makes the code less readable and more fragile. The reason is simple: the calling code starts knowing too much about your object’s internals and must remember what and how to lock.
It is much nicer when the object is responsible for its own correctness: “inside me there is Mutex, outside there is a simple API”. It is like a cafe: you are not required to go to the kitchen and control the oven temperature to get cheesecake.
From an architecture standpoint, this also helps keep invariants close to the data and avoids smearing synchronization across the whole project.
10. Typical mistakes when working with Mutex.withLock
Mistake #1: a too-wide critical section (“let’s put everything under the lock; it’s more reliable”).
Usually it looks like this: you took withLock, and inside you did computations, report formatting, and println, and maybe delay() “for simulation”. Formally it is safe, but in fact you turn Mutex into a queue where one coroutine holds the lock for a long time and the others idle. As a result you get “why doesn’t parallelism speed up the program?”, even though you turned it off yourself.
Mistake #2: protecting a variable instead of an invariant, and therefore placing withLock in the wrong place.
Often someone sees balance and thinks “I need to protect the line balance -= amount”. But the problem is that the invariant “the balance must not go negative” depends on the check if (balance >= amount). If withLock covers only the subtraction, two coroutines can still pass the check at the same time and both withdraw. withLock must cover the entire “checked → changed” block.
Mistake #3: multiple different Mutex instances for the same state.
Sometimes two locks appear in a project “just in case”: one in add, another in snapshot. As a result, you accidentally create the illusion of safety: add and snapshot each synchronize “with themselves” but not with each other. If the state is one, then the protection must be one (or you must very clearly split the state into independent parts, which for a beginner is almost always premature).
Mistake #4: hiding runBlocking inside a helper function so you “don’t have to think about suspend”.
This is one of the most expensive mistakes in terms of consequences. Your helper turns into a hidden blocking call: it can be called “anywhere”, but at the cost of blocking a thread and unexpected behavior. In a coroutine application, such a helper is especially dangerous: it can block a pool thread and degrade the execution of other coroutines. The right path is to make the helper suspend and honestly require a coroutine context from the calling code.
Mistake #5: returning an internal mutable collection to the outside, even if everything is protected by Mutex internally.
If your ExpenseLedger returns MutableList<Expense>, external code can start mutating the list without any Mutex. Formally you “used Mutex”, but in practice you exposed the state “to everyone”. It is much safer to return a snapshot (toList()), and perform all mutations only through methods that use withLock themselves.
GO TO FULL VERSION