https://kotlinlang.org logo
#coroutines
Title
# coroutines
v

vineethraj49

04/13/2021, 3:37 AM
is there a way to force
withContext(<http://Dispatchers.IO|Dispatchers.IO>)
onto a new thread? applies to
GlobalScope.future(<http://Dispatchers.IO|Dispatchers.IO>)
etc as well
z

Zach Klippenstein (he/him) [MOD]

04/13/2021, 3:45 AM
Why do you need to?
v

vineethraj49

04/13/2021, 3:52 AM
hmmm assume I have 4 default dispatcher workers; and I ended up making a blocking call on all of them like
CompletableFuture.get()
DefaultDispatcher-worker-1 .get() DefaultDispatcher-worker-2 .get() DefaultDispatcher-worker-3 .get() DefaultDispatcher-worker-4 .get() now unfortunately, due to "reasons", these completablefutures are from
GlobalScope.future(<http://Dispatchers.IO|Dispatchers.IO>) { }
and none of these can spawn because
<http://Dispatchers.IO|Dispatchers.IO>
should not context switch, but because all DefaultDispatcher-workers are blocked, there's a deadlock there are obviously better and correct-er ways of fixing this; but out of curiosity, if
<http://Dispatchers.IO|Dispatchers.IO>
spawn wasn't blocked on
Dispatchers.Default
this could probably be avoided
r

rocketraman

04/13/2021, 4:26 AM
Don't make blocking calls like
CompletableFuture.get()
on the default dispatcher. Use the suspending
await
extension for `CompletableFuture`: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-jdk8/.
v

vineethraj49

04/13/2021, 6:32 AM
well, duh. but that's not what this question's about.
👎 2
😑 1
e

elizarov

04/13/2021, 9:29 AM
There's no way to force a context switch here. You can try to avoid deadlock by creating a separate dispatcher with its own pool of threads, but, of course, writing code so that it is not deadlock-prone in the first place is better.
👍 1
v

vineethraj49

04/13/2021, 10:46 AM
I know this seems like an XY problem at first, but this is bad and botched attempts at mingling blocking and non-blocking code that has accumulated over two years; and there's no way to identify or fix all of it at once. thanks for clearing that up, I will look into putting these on a separate dispatcher apart from fixing the obvious instances of blocking calls on a non-blocking context.
r

rocketraman

04/13/2021, 1:07 PM
Have you tried using Blockhound to identify the blocking calls? https://github.com/reactor/BlockHound. Coroutines integration via kotlinx-coroutines-debug: https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-debug/.
3 Views