Hi team, I am working with my company's team in h...
# coroutines
l
Hi team, I am working with my company's team in helping migrate from Scala to Kotlin. But, we have some difficulty in interop. Let's say we rewrote a Scala lib into a Kotlin one and it works great in Kotlin APIs but now we wish to use it in Scala applications. We want to expose Futures as part of contract and this is the code sample I initially proposed:
Copy code
override fun getCmsText(
    languageId: Int,
    cmsId: Int,
    origin: String,
): CompletableFuture<String> {
    return CoroutineScope(Dispatchers.IO).future {
        service.getCmsText(languageId, cmsId, origin) // service.getCmsItem is a suspendable function
    }
}
Scala devs are concerned that Dispatchers.IO will initialize a separate thread pool just for this library and would rather reuse the threads they already have. If we use Dispatcher.Default would that prevent creating of yet another pool for Coroutines?
s
• Dispatchers.Default and Dispatchers.IO use the same underlying thread pool. It starts out with one thread per core, but it will grow as you make more use of Dispatchers.IO. • If your function is a suspending function, there's no need to use Dispatchers.IO. It's specifically designed for non-suspending functions that block their thread. • If you have an existing thread pool, you can also consider using it as a coroutine dispatcher. Just call
executor.asCoroutineDispatcher()
.
👍 1
j
What pool was the original Scala code using? You could use the same
👍 1
s
CoroutineScope(<http://Dispatchers.IO|Dispatchers.IO>)
isn't a great solution. If you really want a job with no parent,
GlobalScope.future(dispatcher)
makes the intent clearer.
👍 1
3
l
Thank you for info guys, I will take this to my team
u
If you use coroutines, I’d say chances are that Dispatchers.IO or any other thread pool is being used further down the line. Do you know which dispatchers are being used by
getCmsText
?
l
@uli No Dispatcher was specified inside, this is why we have to do it at this level during interop
👍 1
u
As @Sam mentione:
• If your function is a suspending function, there’s no need to use Dispatchers.IO. It’s specifically designed for non-suspending functions that block their thread.
What does
getCmsText
suspend on? Do you need a dispatcher at all? Let’s assume as an example, you are using okhttp. Then blocking operations will be scheduled to okhttp’s own thread pool. If at all developed by the conventions,
getCmsText
as a suspend function should not block any of your threads. It would either use non-blocking IO or make sure blocking operations are scheduled to some background threads.
In case
getCmsText
obays to the conventions, You are fine with
Dispatchers.Unconfined
Then the only question is, does
getCmsText
itself introduce a thread pool your Scala friends would object to.