hardikm9850 / Android-Playground

0 stars 0 forks source link

Dispatchers.IO vs Dispatchers.Default #6

Open hardikm9850 opened 9 months ago

hardikm9850 commented 9 months ago

Dispatchers.Default is limited to the number of CPU cores (with a minimum of 2) so only N (where N == cpu cores) tasks can run in parallel in this dispatcher.

On the IO dispatcher there are by default 64 threads, so there could be up to 64 parallel tasks running on that dispatcher.

The idea is that the IO dispatcher spends a lot of time waiting (IO blocked), while the Default dispatcher is intended for CPU intensive tasks like computing a mathematical equation, where there is little or no sleep.

Dispatchers.IO and Dispatchers.Default share the same thread pool so that switching between them doesn't require switching threads, but that is just an optimisation. Conceptually you can think of them as different thread pools. One with a thread for each CPU core (Dispatchers.Default), and the other with kotlinx.coroutines.io.parallelism as the number of threads (Dispatchers.IO).

It should be noted that Dispatchers.Default exists because if your coroutines are CPU bound then running them on more threads than you have cores just wastes time on context switching and thread overhead, but you still need more threads than cores if you're doing blocking IO, hence Dispatchers.IO.