https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Animesh Sahu

11/15/2019, 5:10 AM
Also what is difference between Dispatchers.IO and Dispatchers.Default
Copy code
fun main() = runBlocking<Unit> {
	launch(Dispatchers.Default) {
		println("Default               : I'm working in thread ${Thread.currentThread().name}")
	}
	launch(<http://Dispatchers.IO|Dispatchers.IO>) {
		println("IO                    : I'm working in thread ${Thread.currentThread().name}")
	}
}
Output:
Copy code
Default               : I'm working in thread DefaultDispatcher-worker-1
IO                    : I'm working in thread DefaultDispatcher-worker-3
b

bdawg.io

11/15/2019, 5:13 AM
They share threads until too many threads are required. The difference is the maximum number of threads available. Default:
It is backed by a shared pool of threads on JVM. By default, the maximum number of threads used by this dispatcher is equal to the number of CPU cores, but is at least two.
IO:
Additional threads in this pool are created and are shutdown on demand. ... It defaults to the limit of 64 threads or the number of cores (whichever is larger).
By sharing threads, you are able to reduce the number of context switches (one of the most costy overheads of coroutines).
a

Animesh Sahu

11/15/2019, 5:18 AM
@bdawg.io So if there is 4 core processor and 4 long running tasks in io is dispatched, then there is no availability in default to run till one of the io is finished
b

bdawg.io

11/15/2019, 5:21 AM
They share pools, but not limits. Since there are 0 "default" threads currently (in that scenario), it will allocate a new one for "default" dispatcher work. The other 4 threads are "io" threads, but will be returned to the pool to be claimed by IO or Default once it completes.
So they share the pool, but the dispatcher still tracks the number of threads being used by it. By having a shared pool, there's a chance the threads can be reused by either of the dispatchers
a

Animesh Sahu

11/15/2019, 5:25 AM
Ohh, thanks
I love how coroutines manages stuffs 😛
e

Evgeniy Zaharov

11/15/2019, 8:13 AM
if they share threads, what will be if I run multiple long blocking tasks in IO dispatchers? Threads from Dispatchers.Default will be not available for a long time?
a

Animesh Sahu

11/15/2019, 8:38 AM
No he already said that there is no connection between them, they just borrow thread from the pool for reuse. IO would not disturb Default dispatcher, their limits are discrete.
e

Evgeniy Zaharov

11/15/2019, 8:44 AM
ohh, I think now I understand. Thanks!
10 Views