How to correctly make blocking calls in Kotlin Cor...
# feed
h
How to correctly make blocking calls in Kotlin Coroutines? It might suprise you, but IO dispatcher is not the best answer! Learn about it in this new article by @marcinmoskala. https://kt.academy/article/interop-blocking-to-coroutines
a
In the blog it says that IO is the best answer
m
This post says IO is not the best answer
k
<http://Dispatchers.IO|Dispatchers.IO>.limitedParallelism(n)
is the best answer?
m
There is no one best answer, it is one section in the article. I felt I presented it clearly.
👍 1
a
What is the reason that using Loom dispatcher does not cause the issues you mention? In the end the amount of threads is limited right, whether or not it is abstracted away with coroutines or virtual threads?
m
It is because in look threads get blocked, so just like in Kotlin Coroutines you can have thousends of suspended coroutines in a single thread, in Loom you can have thousends of blocked threads using only one real thread.
a
But how is that better than coroutines?
m
Better when you need to use a blocking API
1
w
There's an important API that I think must be mentioned in this topic. It's
runInterruptible {}
, and I've been waiting for a long time for someone to post an article about whether
runInterruptible
is more efficient on virtual threads because I've been procrastinating investigating it myself :p Naively I'd expect
runInterruptible
to be orders of magnitude more efficient on virtual threads, and it should be a no-brainer to wrap all blocking IO calls in a virtual thread dispatcher +
runInterruptible
. But my rudimentary benchmark doesn't show as much of a performance improvement as I expected. (I've attached my benchmark result of cancelling a bunch of
runInterruptible
coroutines using
<http://Dispathers.IO|Dispathers.IO>
and a virtual thread dispatcher, but please take it with a bucket of salt! This is NOT a proper benchmark)