...

/

More on Dispatchers

More on Dispatchers

Learn about some more dispatcher types.

We need to consider the shared state problem for all dispatchers using multiple threads. Notice that in the example below, 10,000 coroutines are increasing i by 1. So, its value should be 10,000, but it’s a smaller number. This is a result of a shared state (i property) modification on multiple threads simultaneously.

package kotlinx.coroutines.app
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

var i = 0

suspend fun main(): Unit = coroutineScope {
    repeat(10_000) {
        launch(Dispatchers.IO) { // or Default
            i++
        }
    }
    delay(1000)
    println(i) // ~9930
}
Shared state problem

There are many ways to solve this problem (most will be described in the “The Problem with Shared State” chapter), but one option is to use a dispatcher with just a single thread. We don’t need any other synchronization if we use just a single thread at a ...