1. Progress: when “there’s no error,” but everything is bad
If you’re used to single-threaded code, you likely have a simple model of the world: if the program breaks, you’ll get an exception. If there’s no exception, it works. Concurrent code brutally breaks that logic. A program may not crash, may not complain, may not print anything suspicious—and still never finish, or finish ten times slower, or “stick” in some weird state.
To talk about this concretely, we need a criterion: progress. Progress is when the system makes useful steps: processes commands, transfers money, updates a counter, completes tasks. If coroutines are alive but there is no progress (or it “shows up only on holidays”)—that’s a symptom of synchronization or design problems.
It helps to keep three “anti-progress” states in mind:
| Problem | What happens in plain words | Typical symptom |
|---|---|---|
| Deadlock | Everyone waits for each other, and nobody can continue | “Sometimes it hangs forever” |
| Livelock | Everyone is actively bustling and yielding, but there is no result | “CPU is doing something, but the point is zero” |
| Starvation | Someone constantly “doesn’t get their turn” and barely runs | “Some tasks run, others starve” |
Next, we’ll go through each one using small Kotlin coroutine examples and Mutex.
2. Deadlock: “you first” — “no, you first”
Deadlock sounds like a rock band name, but it’s more like a tragicomedy genre. In a deadlock, you have multiple participants (coroutines/threads) that have acquired resources (for example, a Mutex) and are now waiting for each other’s resources. Nobody releases what they already hold because “I still need it,” but getting the “next thing” is impossible because it’s held by someone else—and they are waiting too.
The classic way to get a deadlock is to acquire multiple locks in different orders in different parts of the program. This is not “exotic”; it’s a common everyday case when you do a transfer between two accounts: you must lock both accounts so the transfer is atomic.
Let’s imagine our practical mini-app: a console “mini-bank” with accounts and transfers. Each account will have its own Mutex.
Scaffold: an account and two Mutex locks
Let’s build a simple model. What matters here is that Account stores the mutex right next to the balance—so we immediately demonstrate the idea “one piece of state — one lock.”
import kotlinx.coroutines.sync.Mutex
data class Account(
val id: Int,
var balance: Int,
val mutex: Mutex = Mutex()
)
Now let’s create a pair of accounts and a function that transfers money. Important: a transfer is an invariant spanning two objects (“withdraw from one and deposit into the other”), so we need to keep both sides under control.
Deadlock example: two transfers in opposite directions
Here is the “bad” version of a transfer: it first locks from, then to. At first glance, it looks logical.
import kotlinx.coroutines.sync.withLock
suspend fun transferDeadlock(from: Account, to: Account, amount: Int) {
from.mutex.withLock {
to.mutex.withLock {
from.balance -= amount
to.balance += amount
}
}
}
And now we run two transfers in parallel: A -> B and B -> A.
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val a = Account(id = 1, balance = 100)
val b = Account(id = 2, balance = 100)
val j1 = launch(Dispatchers.Default) { transferDeadlock(a, b, 10) }
val j2 = launch(Dispatchers.Default) { transferDeadlock(b, a, 20) }
j1.join()
j2.join()
println("a=${a.balance}, b=${b.balance}") // sometimes it won't print at all
}
Why “sometimes”? Because deadlock is often a scheduling race: if j1 managed to lock a, and j2 managed to lock b, then next:
- j1 waits for b.mutex
- j2 waits for a.mutex
And that’s it. No progress.
You can visualize it like this:
flowchart LR
J1["j1 holds lock(A)"] -->|"wants lock(B)"| B["lock(B) is taken"]
J2["j2 holds lock(B)"] -->|"wants lock(A)"| A["lock(A) is taken"]
B -->|"held by j2"| J2
A -->|"held by j1"| J1
Key idea: deadlock is not a runtime error; it’s a design error in lock acquisition order. In that sense, it’s more insidious than exceptions: there’s no stack trace—just “silence.”
Prevention: a single lock acquisition order
The simplest and strongest rule against deadlocks involving multiple locks: always acquire locks in the same order everywhere in the code.
For example: always lock the account with the smaller id first, then the larger one. Then the system simply cannot produce a wait cycle “A waits for B, B waits for A,” because everyone moves in one direction.
import kotlinx.coroutines.sync.withLock
suspend fun transferOrdered(a1: Account, a2: Account, amount: Int) {
val first = if (a1.id <= a2.id) a1 else a2
val second = if (a1.id <= a2.id) a2 else a1
first.mutex.withLock {
second.mutex.withLock {
a1.balance -= amount
a2.balance += amount
}
}
}
And running it:
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val a = Account(1, 100)
val b = Account(2, 100)
val j1 = launch(Dispatchers.Default) { transferOrdered(a, b, 10) }
val j2 = launch(Dispatchers.Default) { transferOrdered(b, a, 20) }
j1.join(); j2.join()
println("a=${a.balance}, b=${b.balance}") // a=110, b=90 (or the other way around depending on amounts)
}
Note: we did not add delay() “just in case.” Deadlock is not fixed by “magic sleep”; it’s fixed by strict rules.
3. Starvation: “everyone works,” but someone almost never does
Starvation is a situation where the system as a whole seems to move, but a particular task/coroutine consistently fails to get access to a resource (or gets it so rarely that the business logic “dies slowly”). In real life, it’s like standing in a coffee shop line where someone keeps cutting in front of you, and you’ve been holding the same ticket for three hours.
In coroutines, starvation often happens not because someone is malicious, but because we:
- hold a Mutex for too long,
- do a long operation under the lock,
- or simply build a “hot loop” around the lock.
It’s important to understand: Mutex protects correctness, but it does not guarantee fairness in the sense of “everyone gets an equal share on time.” Therefore, critical-section design is not only about correctness, but also about performance.
Bad example: a long delay() under a Mutex
Let’s return to our mini-bank. Suppose there is a “grant bonus” operation (hypothetically) that, for some reason, introduces a delay (for example, waiting for an external step). The delay itself is not the problem. The problem is when the delay happens inside withLock.
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.withLock
suspend fun bonusBad(account: Account) {
account.mutex.withLock {
delay(200) // we hold the lock while we "wait"
account.balance += 1
}
}
If transfers run in parallel, they’ll start to “starve”: each transfer will wait while the bonus “sleeps.” Nobody “dies,” but the program becomes sticky, like an IDE on an old laptop.
Good style: a short critical section
A common correct thought is: “If I’m waiting, then I’m not changing anything. So why am I holding the lock?”
import kotlinx.coroutines.delay
import kotlinx.coroutines.sync.withLock
suspend fun bonusGood(account: Account) {
delay(200) // wait outside
account.mutex.withLock {
account.balance += 1
}
}
Yes, this is not always possible: sometimes you must “wait” exactly between a read and a write, and then the invariant is more complex. But in most everyday cases, this is a direct improvement.
How starvation looks “to the naked eye”
Starvation is unpleasant because logs can make it look like “everything works.” It’s just that some operations start to “think for a very long time sometimes.” This is typically diagnosed by symptoms like:
- some coroutines reliably complete quickly,
- others “hang” for disproportionately long,
- overall throughput drops.
And almost always the reason is an overly wide critical section or heavy work inside withLock.
4. Livelock: “polite” coroutines with no results
Livelock is similar to deadlock in that there is no progress, but it differs in dramaturgy: in a deadlock everything is frozen, while in a livelock everything is actively moving—just uselessly.
A common cause of livelock is trying to be “too polite”: “if it didn’t work, I’ll release and try again later,” but both sides do it synchronously and obstruct each other forever.
To demonstrate livelock, we’ll use tryLock(): an attempt to acquire a Mutex without waiting. If the lock is taken, it returns false. This is a familiar idea from atomics: “tried — failed — rolled back,” just at the lock level.
A naive “polite” transfer with tryLock()
Let’s make a transfer that tries to acquire both locks. If it fails, it releases what it acquired and repeats.
import kotlinx.coroutines.delay
suspend fun transferLivelock(from: Account, to: Account, amount: Int) {
while (true) {
if (from.mutex.tryLock()) {
try {
if (to.mutex.tryLock()) {
try {
from.balance -= amount
to.balance += amount
return
} finally {
to.mutex.unlock()
}
}
} finally {
from.mutex.unlock()
}
}
delay(1) // "yield" so we don't spin the CPU
}
}
The code looks reasonable, but now imagine two coroutines:
- the first wants A -> B,
- the second wants B -> A.
Both can fall into a rhythm:
- acquire “their” first lock
- fail to get the second lock
- release and wait delay(1)
- repeat at the same time
They are not standing still; they are running in circles. Zero progress.
How to tell livelock from deadlock
Deadlock often looks like “silence”: it hangs and that’s it.
Livelock more often looks like “something is happening”: CPU usage can be noticeably high, logs can get spammed, but the state does not change.
If you add a debug println("try..."), you may get an endless stream of lines. This is, by the way, a separate pain point: logging itself becomes a slowdown, and you end up treating symptoms rather than the cause.
Livelock prevention: asymmetry
Livelock breaks if we add asymmetry. There are many ways, but the idea is one: both sides must not behave identically.
The simplest and most practical option at a learning level is a single acquisition order (as with deadlock). Then even with tryLock() you won’t get an endless “polite fight”: everyone tries to take first and then second.
Let’s make a version ordered by id and add a small random backoff to break retry synchronization:
import kotlin.random.Random
import kotlinx.coroutines.delay
suspend fun transferTryOrdered(a1: Account, a2: Account, amount: Int) {
val first = if (a1.id <= a2.id) a1 else a2
val second = if (a1.id <= a2.id) a2 else a1
while (true) {
if (first.mutex.tryLock()) {
try {
if (second.mutex.tryLock()) {
try {
a1.balance -= amount
a2.balance += amount
return
} finally {
second.mutex.unlock()
}
}
} finally {
first.mutex.unlock()
}
}
delay(Random.nextLong(1, 5)) // break the "marching in step"
}
}
Yes, this is a bit more complex than just withLock. And that’s an important moral too: once you start “manual lock management,” you’re in a higher-risk zone. Sometimes it’s easier to go back to withLock and a strict ordering.
How not to design a trap: habits that save you
If we reduce deadlock/livelock/starvation prevention to one idea, it sounds like this: reduce the number of reasons coroutines have to compete for resources at all.
In the previous lecture about confinement/actor, we saw a design where a single owner mutates state and everyone else sends messages. Such a design often reduces the risk of deadlock and starvation “by construction,” because you don’t have “two locks, two owners, two orders.” Even if the owner uses a Mutex internally, it’s a local story, not a web of mutual waiting.
If you do stay with Mutex, then the most stable set of habits looks like this:
flowchart TD
A["Need synchronization?"] --> B["Can you remove shared state via confinement?"]
B -->|yes| C["Actor: one owner of the state"]
B -->|no| D["Do you need multiple locks at the same time?"]
D -->|yes| E["Single acquisition order and minimal section"]
D -->|no| F["One Mutex and a short withLock"]
This diagram is not “official,” but it disciplines your brain well: before adding a second Mutex, ask yourself whether you’re creating a future deadlock “on an installment plan.”
5. Typical mistakes
Mistake #1: acquiring multiple Mutex locks in different orders “in different places, just a little.”
This is the most common deadlock source. In one method you lock A then B; in another you lock B then A, because “it reads better that way.” Then the program sometimes hangs forever, and you start suspecting everything: GC, JIT, the phase of the moon, and your neighbor’s microwave. This is fixed not by debugging, but by a rule: one acquisition order for the whole project (for example, by id).
Mistake #2: holding a Mutex during long operations (I/O, delay, heavy computation).
This is how you grow starvation yourself. Even if deadlock is impossible, the system will degrade: one coroutine holds the lock for a long time, the others wait, and it feels like “everything is slow,” even though correctness is formally preserved. The right mindset: under the lock, keep only what truly must be atomic.
Mistake #3: trying to “fix hangs” by sprinkling delay() in random places.
delay() can accidentally mask the problem (especially races), and with deadlocks it may seem “better” simply because coroutine scheduling changed. That’s not a solution. The solution is critical-section boundaries, a single lock order, or switching the design to confinement.
Mistake #4: manually writing tryLock/unlock without try/finally.
In the examples above, try/finally looks tedious, but this is the case where tediousness saves you. Any early return, any exception, any “if it didn’t work” branch—and you risk not releasing the lock. One forgotten unlock() turns the system into “eternal waiting” and makes the root cause hard to reproduce.
Mistake #5: fighting livelock with identical strategies on both sides.
If two coroutines “politely yield” in the same way, they can yield in sync forever. Livelock is fixed with asymmetry: a single acquisition order, random backoff, or an architectural solution where there is simply no competition for the resource (confinement/actor).
Mistake #6: assuming that because we use Mutex, it will “fairly distribute the queue.”
Mutex provides mutual exclusion, but it does not guarantee that each coroutine will get the resource on time. If one part of the code constantly holds the lock for long periods or grabs it very frequently, others may starve. So Mutex is a correctness tool, while “fairness” and “throughput” remain the responsibility of the design.
GO TO FULL VERSION