https://kotlinlang.org logo
Title
c

coder82

07/26/2019, 9:40 AM
Hi guys, I am building an API using Kotlin and KTOR. I have to connect to a legacy system which offers only blocking calls, so I guess even if I use the coroutines, ultimately a thread from the pool will be blocked on these calls right? I can't do otherwise. So if I use for example "withContext", and use a specific context with a pool of 20 threads, i can never serve more than 20 calls in parallel right? Ultimately want I want to do is to respond with some sort of backpressure message when these 20 threads are all busy. What do you reckon? the legacy system doesn't offer asynchronouse callbacks so i cannot build something with suspendCoroutine around it so I am kind of forced to pool threads it's be nice to have somebody's opinion on it
d

dave

07/26/2019, 9:53 AM
#ktor
m

Mike

07/26/2019, 12:44 PM
I think this is one point of coroutines. You make your call to the blocking service in a coroutine. The coroutine 'pauses', releasing the thread. Once a response is received, the coroutine continues its work on the next available thread. My understanding is fairly basic right now, but if done correctly, this is what you can achieve.
c

coder82

07/26/2019, 12:46 PM
yes but the thread within the coroutine is being held blocked against the legacy blocking API
your reasoning would work if I dealt with a fully asynch API where I can build my continutation resume using their callbacks
not sure but, my best effort is what I described above
@gildor
m

Mike

07/26/2019, 2:42 PM
Maybe ask in #coroutines too. They will know much more than I do about coroutines, and if this is possible at all.
g

gildor

07/27/2019, 9:30 AM
@coder82 yes, your assumption is correct, if you block, thread and coroutine will be also blocked I don't think that there is public API of disapatchers that would give you callback about blocking all the threads, so you have to provide own way detect it, or by writing own dispatcher, but maybe would be even easier to do that on level of custom thread pool executor (that can be used by coroutines by converting it to Dispatcher), so you easily can get amount of active threads using getActiveCount method of Thread pool, and just use execute() as hook when coroutine is dispatched Would be nice to use Dispatcher thread pool, it's more optimized and allows reuse threads, but there is no pilublic API for it and for legacy code approach with custom executor service looks as reasonable solution