Satyam Agarwal
04/28/2021, 8:00 PMGlobalScope.launch { … }
I read this article https://elizarov.medium.com/the-reason-to-avoid-globalscope-835337445abc which makes sense, and I almost always use withContext(AppropriateDispatcher) { … }
to offload heavy jobs.
I have a ktor server that receives around 260 req/sec and logs request and responses while receiving and responding, along with actual response.
This is done via an interceptor. Now I don’t care much about logging, so I was thinking to do something like GlobalScope.launch(MDCContext()) { interceptor.request.log(...) }
so that logging is eventually done, but the interceptor can proceed()
immediately.
In fact, I was thinking to do this to pretty much every logging,
Do you think it is a good way of doing the intention. What can be the consequences in regards to threads and CPU if a lot of logging suddenly starts offloading to GlobalScope ?
Anyone can help me as well 🙂 Any and all feedback is much appreciated.baxter
04/28/2021, 8:01 PMZach Klippenstein (he/him) [MOD]
04/28/2021, 8:04 PMGlobalScope
doesn’t specify a dispatcher, which means that in most cases the Default
dispatcher will end up getting used. So whatever that implies about thread behavior will apply to GlobalScope
.nicholasnet
04/28/2021, 10:28 PMuli
04/29/2021, 7:31 AMobject LoggerScope = CoroutineScope(...+ SupervisorJob())
Or better inject it using DIelizarov
04/29/2021, 8:46 AMGlobalScope.launch { log(...) }
is an exceptionally bad idea. First of all, you can get your back-to-back log statements misordered, vastly complicating future trouble-shooting that logging was supposed to help with in the first place. Now, you probably were trying to solve a problem of "logging being slow" by offloading it to the background, but instead you've created a situation where if your logging is indeed slow, then its slowness will manifest in your app running out of memory, making it way harder to figure out why is that your app is not working as good as indented.elizarov
04/29/2021, 8:49 AMelizarov
04/29/2021, 8:51 AMSatyam Agarwal
04/29/2021, 9:00 AMSatyam Agarwal
04/29/2021, 9:01 AMSatyam Agarwal
04/29/2021, 9:02 AMlouiscad
04/29/2021, 9:27 AMyourScope.actor
would probably work best for your use case @Satyam AgarwalSatyam Agarwal
04/29/2021, 9:51 AMnicholasnet
04/29/2021, 7:35 PM