🐦 Kotlin
Advanced
What is a Mutex in Kotlin coroutines?
Answer
A Mutex (mutual exclusion lock) is a coroutine-friendly synchronization primitive that protects shared mutable state from concurrent access. Unlike Java's synchronized block which blocks the thread while waiting for the lock, Mutex.withLock { }` suspends the coroutine, freeing the thread for other work. Example: val mutex = Mutex(); mutex.withLock { sharedList.add(item) }. This is crucial in coroutines because you might have many coroutines on a few threads, and blocking a thread waiting for a lock defeats the purpose of coroutines. An alternative is to confine mutable state to a single dispatcher (actor pattern).