Junior — Middle
What methods are used to organize safe concurrent access of coroutines to a resource?
sobes.tech AI
Answer from AI
To safely share access of coroutines to a resource in Android (Kotlin), the following methods are usually used:
- Mutex from kotlinx.coroutines — provides mutual exclusion, allowing only one coroutine to access the resource at a time.
- Channel — for passing data between coroutines, helping to avoid direct shared access.
- Atomic operations — for simple cases where you need to safely update primitive values.
Example of using Mutex:
val mutex = Mutex()
var sharedResource = 0
suspend fun safeIncrement() {
mutex.withLock {
sharedResource++
}
}
This approach prevents data races and ensures correct behavior during parallel execution of coroutines.