Pick the fix
1,000 coroutines each call increment() on Dispatchers.Default. The total is often below 1,000. What's the best fix?
class Counter {
val state = MutableStateFlow(0)
fun increment() {
state.value = state.value + 1
}
}Hint 1 of 1
How many steps is value + 1 followed by a write?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Use state.update { it + 1 } on the StateFlow
Correct. update retries with compare-and-set, so no increment is lost.
Why not the others?
- B Mark the property
@Volatile. That only affects visibility; read-modify-write is still not atomic. - C Run the coroutines with
Dispatchers.IO. IO is also multi-threaded; the race stays. - D Add
yield()before the write. That changes timing but doesn't make the update atomic.