https://kotlinlang.org logo
k

Ka Wing Chin

10/23/2020, 7:10 PM
Hello, I have a question about
Dispatchers
. I created an endless loop to create threads and see how the program will behave.
Copy code
class MainActivity : AppCompatActivity() {

    private val dispatcher: CoroutineContext = <http://Dispatchers.IO|Dispatchers.IO>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val cores = Runtime.getRuntime().availableProcessors()
        println("Cores: $cores")
        println("===============================")

        endlessLoop()
    }

    fun endlessLoop() = runBlocking {
        withContext(dispatcher) {
            println(Thread.currentThread().name)
            while(true) {
                launch {
                    println(Thread.currentThread().name)
                    while(true) {
                        // endless loop
                    }
                }
            }
        }
    }
}
I got a phone with 4 cores and each core can handle 4 threads. If I would run this
Dispatchers.Default
. Then output will be:
Copy code
DefaultDispatcher-worker-1
DefaultDispatcher-worker-2
DefaultDispatcher-worker-3
DefaultDispatcher-worker-4
I get this, because all cores got occupied and working at 100% to get it done and no more tasks are allowed to be added. However if I run it with
<http://Dispatchers.IO|Dispatchers.IO>
which has 64 threads in the pool, it will run all 64 threads. I though it was 4 cores * 4 threads = 16 threads max. Can someone explain me why the program doesn't stop at
DefaultDispatcher-worker-16?
1
a

Adam Powell

10/23/2020, 7:32 PM
The io dispatcher is designed to run tasks that are going to call blocking platform APIs that will block a thread but not consume cpu resources since the kernel won't schedule the thread to run again until the io operation completes
So it's ok to have many more of these operations pending than you have available cpu cores
Things like reading a file or socket
1
2 Views