Coroutine starvation

We'll call both the greedyLongCoroutine() and shortCoroutine() methods 10 times each and wait until they finish:

val latch = CountDownLatch(10 * 2)
fun main(args: Array<String>) {

for (i in 1..10) {
CoroutineFactory.greedyLongCoroutine(i)
}

for (i in 1..10) {
CoroutineFactory.shortCoroutine(i)
}

latch.await(10, TimeUnit.SECONDS)
}

It's obvious that since coroutines are asynchronous, we'll see first 10 lines of the short coroutine then 10 lines of the long coroutine:

Done greedyLongCoroutine 2
Done greedyLongCoroutine 4
Done greedyLongCoroutine 3
Done greedyLongCoroutine 5
Done shortCoroutine 1! <= You should have finished long ago!
Done shortCoroutine 2!
Done shortCoroutine 3!
Done shortCoroutine 4!
Done shortCoroutine 5!
Done shortCoroutine 6!
Done shortCoroutine 7!
Done shortCoroutine 8!
Done shortCoroutine 9!
Done shortCoroutine 10!
Done greedyLongCoroutine 6
Done greedyLongCoroutine 7
Done greedyLongCoroutine 1
Done greedyLongCoroutine 8
Done greedyLongCoroutine 9
Done greedyLongCoroutine 10

Oops... That's not what you would expect. It seems like the long coroutines block the short coroutines somehow.

The reason for this behavior is that there is still an event loop based on the thread pool behind the coroutines. Since the CPU of my laptop has four cores, four long coroutines took all its resources, and until they finish their CPU-bound task, no other coroutine can start. To understand this better, let's dive deeper into how coroutines work. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.82.217