Both give you “one at a time.” They protect different things, fail in different ways, and picking the wrong one produces bugs that only show up under load.

One Turnstile or One Lane? Mutex vs. a Single-Thread Executor on Android
The short version
- A
Mutexguards a region of code. Waiting coroutines suspend, no thread is blocked, and whoever wins may resume on any dispatcher thread. - A single-thread executor guards a thread. Work queues up and runs on one dedicated thread, always the same one.
- If the code must live on a specific thread (a JNI handle, a thread-affine SDK), you want the executor. If you only need to keep a read-modify-write sequence from interleaving, you almost always want the
Mutex. - Neither is a free lunch. The
Mutexhangs silently when misused; the executor leaks or swallows errors silently. Most of this post is about those silences.
Two different promises
People reach for both tools with the same sentence in their head: “I need these calls to not overlap.” That sentence hides a real difference in what is being guaranteed.
A Mutex promises mutual exclusion over a block. Between lock() and unlock(), no other coroutine using the same mutex is inside that block. It says nothing about which thread runs the block, and a coroutine can hop threads inside it if it suspends and its dispatcher resumes it elsewhere.
A single-thread executor promises thread confinement. Every task runs on the same worker, one after another. It says nothing about whether two logical operations can interleave, because a coroutine that suspends gives the thread to the next task in the queue.
The side-by-side below is the reference I keep coming back to.
A single thread is not an atomic step
This is the misconception that causes the most damage, so it comes first.
Suppose a wallet class keeps a balance and records every deposit with a remote ledger:
class CreditsWallet(private val ledger: LedgerApi) {
var balance = 100
private set
suspend fun deposit(amount: Int) {
val before = balance // 1. read
ledger.record(amount) // 2. suspension point
balance = before + amount // 3. write back a possibly stale total
}
}
“I’ll run it on one thread, so there’s no race.” Here is a test that tries exactly that:
@Test
fun `one thread still loses a deposit`() = runBlocking {
val single = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
val wallet = CreditsWallet(FakeLedger(delayMs = 20))
try {
withContext(single) {
listOf(30, 50).map { launch { wallet.deposit(it) } }.joinAll()
}
assertEquals(180, wallet.balance) // fails: you get 130 or 150
} finally {
single.close()
}
}
Both children inherit single, so everything runs on one thread. The assertion still fails, because the delay inside FakeLedger.record suspends the first coroutine, the thread picks up the second one, and both captured before = 100. Whichever finishes last wins, and one deposit disappears.
The thread guaranteed that no two statements ran simultaneously. It never promised that your three-step sequence would run contiguously. Suspension points are exactly where contiguity breaks.
There are two honest fixes. The first is to make the critical section a single non-suspending step, so the dispatcher cannot slip anything in:
suspend fun deposit(amount: Int) {
ledger.record(amount) // slow work first, outside any shared-state access
balance += amount // one non-suspending step; atomic on a single thread
}
That works only while everything stays on one thread. The moment someone injects Dispatchers.Default, balance += amount is a data race again. The second fix does not depend on where the code runs:
class CreditsWallet(private val ledger: LedgerApi) {
private val mutex = Mutex()
private var balance = 100
suspend fun deposit(amount: Int) {
ledger.record(amount)
mutex.withLock { balance += amount }
}
suspend fun current(): Int = mutex.withLock { balance }
}
I prefer this one for shared state. It states its own invariant instead of borrowing it from a dispatcher choice made in another file.
Mutex, idiomatically
Three habits cover most of what goes right with Mutex.
Always use withLock. It wraps the body in try/finally, so an exception or a cancellation releases the lock. Bare lock() and unlock() pairs belong in library internals.
Keep the critical section small, except when atomicity demands otherwise. Sometimes check and act really must be one unit. A spend operation is the textbook case: checking the balance, asking the server to authorize, and deducting cannot be split, or two concurrent calls can both pass the check.
suspend fun spend(amount: Int): Boolean = mutex.withLock {
if (balance < amount) return@withLock false
// Lock held across a network call on purpose: check and deduct are one unit.
val approved = withTimeout(3_000) { ledger.authorize(amount) }
if (approved) balance -= amount
approved
}
The withTimeout is not decoration. Every other caller is queued behind this one, so an unbounded call turns one slow request into a frozen feature. When the timeout fires, withLock still releases the lock on the way out.
Remember that Mutex is fair and cancellable. Waiters are served first come, first served, and a coroutine cancelled while waiting for lock() leaves the queue cleanly. That is why a screen that launches work in viewModelScope does not strand a lock when the user navigates away.
Single-thread executor, idiomatically
Reach for an executor when the thread is the constraint. A common Android case is a native engine, reached through JNI, that must be created, used, and released from the same thread:
class NativeRecorder(private val engine: RecorderEngine) {
private val executor = Executors.newSingleThreadExecutor { task ->
Thread(task, "native-recorder").apply { isDaemon = true }
}
private val dispatcher = executor.asCoroutineDispatcher()
suspend fun start(sampleRate: Int) = withContext(dispatcher) {
engine.open(sampleRate)
engine.start()
}
suspend fun nextFrame(): ShortArray = withContext(dispatcher) { engine.pull() }
suspend fun shutdown() {
// Teardown must still run on the owning thread, even if the caller was cancelled.
withContext(NonCancellable + dispatcher) { engine.release() }
dispatcher.close() // shuts the executor down
}
}
A few choices here are deliberate.
-
Build the executor yourself. A custom
ThreadFactorygives the thread a name that shows up in traces and lets you decide about the daemon flag. The convenience factorynewSingleThreadContextis marked as a delicate API precisely because it makes leaking a thread easy. -
Bridge with
asCoroutineDispatcher(), then usewithContextat the call sites. Callers stay in ordinary suspending code and never touch the executor directly. -
Release on the owning thread. The
engine.release()call runs through the same dispatcher, so the native side sees the same thread from open to close. -
Use
NonCancellablefor teardown. Ifshutdown()is invoked from a scope that is already cancelled, a plainwithContextthrows before running its block, and the engine is never released.
If all you need is “no two of these run at once” and you do not need a particular thread, Dispatchers.IO.limitedParallelism(1) gives you serialized execution without owning a thread. Be clear about what it does not give you: it does not promise the same thread each time, so it is not a substitute for thread affinity.
Failure modes in production
The cheat sheet below summarizes the six I see most. The sections after it explain the ones that deserve code.
1. The lock that waits on itself
Mutex is not reentrant. A coroutine that holds the lock and calls another function that takes the same lock suspends forever, waiting for a release only it can perform. There is no exception, no log line, and the ANR (if this was on the main path) is the first symptom anyone sees.
class Ledger {
private val mutex = Mutex()
private val entries = mutableListOf<Entry>()
suspend fun transfer(from: String, to: String, amount: Int) = mutex.withLock {
entries += Entry(from, -amount)
entries += Entry(to, amount)
audit() // takes the same mutex: never returns
}
suspend fun audit() = mutex.withLock {
check(entries.sumOf { it.delta } == 0) { "ledger out of balance" }
}
}
The fix is structural, not clever. Public functions lock once; private helpers assume the lock is held and say so in their name.
suspend fun transfer(from: String, to: String, amount: Int) = mutex.withLock {
entries += Entry(from, -amount)
entries += Entry(to, amount)
auditLocked()
}
suspend fun audit() = mutex.withLock { auditLocked() }
private fun auditLocked() {
check(entries.sumOf { it.delta } == 0) { "ledger out of balance" }
}
A cheap test catches this class of bug: call every public method from every other public method inside a withTimeout, and fail on timeout.
2. Slow work inside the lock
Head-of-line blocking is the quiet cousin of the deadlock. The lock is correct, the code is correct, and the screen is still frozen because the one coroutine in the critical section is waiting on a slow endpoint. Where atomicity does not require holding the lock across I/O, split the work into three phases: snapshot under the lock, do the slow part outside, commit under the lock.
suspend fun refreshQuota() {
val stamp = mutex.withLock { version } // snapshot
val fresh = api.fetchQuota() // slow, no lock held
mutex.withLock {
if (version == stamp) quota = fresh // commit only if nothing changed
}
}
3. Executors that swallow or crash
The two ways to hand work to an executor treat exceptions differently, and both surprise people.
executor.submit { error("lost forever") } // failure is stored in the Future; nobody sees it
executor.execute { error("loud") } // reaches the thread's uncaught-exception handler
With submit, the error sits inside a Future that nobody reads. With execute, the uncaught exception reaches the thread's handler, which on Android normally ends the process. Inside a coroutine dispatcher the picture changes again: the coroutine machinery catches the exception and routes it through the job hierarchy. The rule of thumb is to decide on purpose. Catch and report inside the task, or read the result, and never let the choice be an accident of which method you called.
4. The thread nobody shuts down
A thread from newSingleThreadExecutor stays alive while idle, and it holds references to everything its tasks captured. If the owner is a screen-scoped object and the executor is never shut down, the thread and those references live as long as the process. Pair every executor with an owner that closes it: shutdown() for the raw executor, close() for the coroutine dispatcher built on it.
5. Waiting on your own queue
val worker = Executors.newSingleThreadExecutor()
worker.submit {
val inner = worker.submit { compute() } // queued behind the task that is running
inner.get() // blocks the only worker: deadlock
}
The inner task cannot start until the outer one finishes, and the outer one will not finish until the inner one does. With a pool of one, every blocking get() on the same executor is a self-deadlock. Chain the work, or pass a callback.
Android-specific notes
-
The main thread. A suspended
Mutex.withLockdoes not block the main thread, which is the point. A blocking primitive combined withrunBlockingon the main thread absolutely does, and that is how lock bugs turn into ANRs. -
Do not suspend inside
synchronized. The compiler rejects it, and aReentrantLockheld across a suspension is worse, because the coroutine may resume on another thread and then fail to unlock a lock owned by the first. -
Testing. A
Mutexdoes not care which thread runs it, soStandardTestDispatcherand virtual time work fine. A thread-affine design cannot be faked that way. Inject the dispatcher, use a test dispatcher for logic, and add one integration test on the real single-thread dispatcher that assertsThread.currentThread().nameinside the guarded calls. -
Lifecycle. Put the thing that owns a thread in a scope that outlives the screens using it, and run teardown with
NonCancellable, as inshutdown()above. AViewModel's scope is already cancelled by the timeonCleared()runs.
Choosing
A few notes on that flow, since a diagram flattens the nuance.
- Thread first. If a library or native handle demands one thread, nothing else on the list can satisfy it. This is the only question where the executor is the only correct answer.
-
Suspension second. If the guarded section suspends, a blocking lock is off the table.
Mutexis the tool built for that. -
Single values third. A counter or flag does not need a lock object.
AtomicInteger, orMutableStateFlow.update { }when observers care, is shorter and cannot deadlock. -
Otherwise, keep it boring. If nothing suspends and no thread is mandated, a plain
synchronizedblock over a tiny section is the cheapest option. UseMutexthere only if you want one consistent tool across the codebase.
🔚 Closing
The two tools answer different questions. The executor answers where does this run? The Mutex answers who is inside this block right now? Confusing them is how a "thread-safe" wallet ends up with a missing deposit. Treat suspension points as the places where guarantees break, keep critical sections small, close what you open, and write the test that makes the silent failures loud.
Further reading
- The Kotlin guide on shared mutable state and concurrency covers thread confinement and
Mutexfrom the language's own perspective: https://kotlinlang.org/docs/shared-mutable-state-and-concurrency.html - The
MutexAPI reference documents fairness, reentrancy, andtryLock: https://kotlinlang.org/api/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines.sync/-mutex/
🔐 Master Android Architecture: Volume 1, Foundations and Core Architecture
Most Android architecture advice is a diagram and a list of rules. This book teaches the judgment behind them. You build NowReading from an empty project into an offline-first app, one decision at a time. It covers the principles behind Google’s layered architecture, then every layer in depth: Compose and state holders, MVI, navigation, the domain layer, Room and DataStore, networking, offline-first sync, Hilt, coroutines and Flow, background work and error handling. Every chapter opens with a realistic failure and ends with pitfalls, trade-offs, review questions and an exercise.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover






Top comments (0)