I have a problem with await in Kotlin, if I use only 2 await
s, this runBlocking
block works for 10 seconds, but when I try to use 4 await
s, 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
}
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With