Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Suspend function blocks main thread

I'm having a hard time understanding coroutines. This is a very simple setup. Both longComputation and delay are suspend functions. The first one blocks the main thread, the latter doesn't. Why?

CoroutineScope(Dispatchers.Main).launch {
    val result = longComputation() // Blocks
    delay(10_000) // Doesn't block
}
like image 921
Kuno Avatar asked Aug 24 '26 19:08

Kuno


1 Answers

That depends. What does longComputation do exactly? When you mark a function as suspend, this does not mean you can't include blocking code in it. For instance, have a look at this one:

suspend fun blockingSuspendFunction(){
    BigInteger(1500, Random()).nextProbablePrime()
}

The code inside the suspend function is obviously something that utilizes the CPU and blocks the caller. By convention, this should not be done because if you call a suspend function, you expect it to not block the thread:

Convention: suspending functions do not block the caller thread. (https://medium.com/@elizarov/blocking-threads-suspending-coroutines-d33e11bf4761)

To make such a function "behave as a suspending function", the blocking has to be dispatched onto another worker thread, which (by recommendation) should happen with withContext:

suspend fun blockingSuspendFunction() = withContext(Dispatchers.Default) {
    BigInteger.probablePrime(2048, Random())
}
like image 183
s1m0nw1 Avatar answered Aug 26 '26 08:08

s1m0nw1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!