Ka Wing Chin
10/23/2020, 7:10 PMDispatchers
. I created an endless loop to create threads and see how the program will behave.
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:
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?
Adam Powell
10/23/2020, 7:32 PM