Search code examples
kotlinkotlin-coroutines

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
    }
}

Solution

  • 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()
    

    2024 Update

    It is almost never necessary to involve your own dispatcher. You can rely on Dispatchers.IO, backed by a flexible thread pool. By default it has up to 64 threads, and that's configurable.