Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More than two awaits in runBlocking

I have a problem with await in Kotlin, if I use only 2 awaits, this runBlocking block works for 10 seconds, but when I try to use 4 awaits, it works for 20 seconds. As I understand, there are only two async threads in runBlocking. How can I increase this count?

fun testFun() {
    val z1 = async { Thread.sleep(10000) }
    val z2 = async { Thread.sleep(10000) }
    val z3 = async { Thread.sleep(10000) }
    val z4 = async { Thread.sleep(10000) }

    runBlocking {
        z1.await()
        z2.await()
        z3.await()
        z4.await() // works 20 seconds
    }
}
like image 648
Nikita Sahan Avatar asked Mar 01 '18 11:03

Nikita Sahan


1 Answers

With async { ... } you let the standard library choose a default context to run your coroutines in. I guess in your case it happens to be a thread pool with just two threads.

To gain control over what happens, use

async(MyDispatcher) { ... }

where, as a simple example, you can define

val MyDispatcher = Executors.newFixedThreadPool(4).asCoroutineDispatcher()

Keep in mind that shutting down the thread pool is now your responsibility:

MyDispatcher.close()
like image 189
Marko Topolnik Avatar answered Oct 01 '22 13:10

Marko Topolnik