Mutex
- Kotlin course
- Advanced
- Lesson 67/83
- 5 min
Learn mutual exclusion with Mutex.
Mutual exclusion with Mutex
Mutex ensures only one coroutine enters a code block at a time. With withLock { } the lock is acquired and released automatically at the end of the block.
Example: val m = Mutex(); m.withLock { counter++ }. Two coroutines do not increment counter at the same time; one waits. withLock releases the lock automatically at the end of the lambda; no try/finally needed. This pattern provides safe access to shared mutable state.
withLock and auto-release
withLock acquires the lock at the start of the lambda and releases it at the end. Even on exception the lock is released; this is safer than managing lock/unlock by hand.
Example: m.withLock { shared.add(item) }. Even if add throws, the Mutex is freed. This pattern makes fault-tolerant concurrent code easier to write; it removes the risk of leaving a lock held by mistake.
Practice A locked block with Mutex
Open main with runBlocking. Create val m = Mutex() and add the call m.withLock { println("locked") }. Do not forget the Mutex and withLock imports.
Starter code
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
// open main with runBlocking
// create Mutex, print with withLockSample solution
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
fun main() = runBlocking {
val m = Mutex()
m.withLock {
println("locked")
}
}Expected output
locked
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does Mutex's withLock method provide?
- Multiple coroutines enter at once
- Single coroutine access Correct answer
- Async call
- No mutex needed
Explanation: withLock provides single coroutine access.
2 Complete the withLock call
val m = Mutex()
m.____ { counter++ }
val m = Mutex()
m.withLock { counter++ }
Explanation: withLock acquires and releases the lock.
3 Match the Mutex parts
| Term | Meaning |
|---|---|
Mutex() |
Lock object |
withLock { } |
Locked block |
counter++ |
Protected op |
auto-release |
Safety |