Bernhard
04/16/2024, 8:40 AMSam
04/16/2024, 8:47 AMGlobalScope
, and use launch()
. But if you also need 2️⃣, you're going to need to block the thread at some point. There's no getting away from that unfortunately. So runBlocking
is the way to go. You probably don't even need the IO dispatcher at that point, since the Spring request will have its own dedicated worker thread which you're free to use for whatever you want during the request. Better to let the runBlocking
function's event loop make use of that thread than just leave it idle while the IO dispatcher does the work.Sam
04/16/2024, 8:48 AMBernhard
04/16/2024, 8:49 AMSam
04/16/2024, 8:50 AMBernhard
04/16/2024, 8:52 AMBernhard
04/16/2024, 8:52 AMSam
04/16/2024, 8:55 AMrunBlocking
. All the better if the blocked thread turns out to be a virtual thread.Sam
04/16/2024, 8:57 AMSam
04/16/2024, 8:58 AM<http://Dispatchers.IO|Dispatchers.IO>
.Sam
04/16/2024, 8:58 AM<http://Dispatcher.IO|Dispatcher.IO>
nor a loom dispatcher should be necessary since no threads (virtual or otherwise) will ever be blocked.Sam
04/16/2024, 8:59 AMBernhard
04/16/2024, 9:00 AMBernhard
04/16/2024, 9:01 AMBernhard
04/16/2024, 9:01 AMBernhard
04/16/2024, 9:01 AMkqr
04/16/2024, 9:03 AMkqr
04/16/2024, 9:03 AMBernhard
04/16/2024, 9:04 AMBernhard
04/16/2024, 9:04 AMSam
04/16/2024, 9:12 AMrunBlocking
without a custom dispatcher, you'll stay on the original thread and won't run into problem 2️⃣.
So in general, the problems in the video don't appear to apply to your situation.
However, you should be aware that any suspending function can choose to use withContext
internally to switch its dispatcher, which would potentially cause problem 2️⃣ to crop up further down the call stack in the Ktor internals. The video talks about how to mitigate this with extra coroutine context elements like MDCContext
.Sam
04/16/2024, 9:19 AMMono
, but perhaps there's more involved to set initial coroutine context and things like that.Bernhard
04/16/2024, 9:24 AMSam
04/16/2024, 9:29 AMSam
04/16/2024, 9:31 AMBernhard
04/16/2024, 10:04 AMSam
04/16/2024, 10:41 AMrunBlocking
and don't ever switch to a different dispatcher, then you'll always be on the same thread with the same thread context you started out with 👍.Bernhard
04/16/2024, 10:43 AMBernhard
04/16/2024, 10:43 AMBernhard
04/16/2024, 10:43 AMSam
04/16/2024, 10:44 AMSam
04/16/2024, 10:44 AMBernhard
04/16/2024, 10:44 AM