If we want to cancel all coroutines in the scope, with structured concurrency, we only need to cancel the parent coroutine and this automatically propagates cancellation to all the child coroutines. It is possible to store a reference to the coroutine started from the global scope and wait for its completion or cancel it explicitly, but it won't happen automatically as it would with a structured one. The coroutines started from the global scope are all independent their lifetime is limited only by the lifetime of the whole application. When using GlobalScope.async there is no structure that binds several coroutines to a smaller scope. The parent coroutine does not complete until all the coroutines Therefore, if the scope corresponds to a coroutine, then The scope automatically waits for completion of all the child coroutines.The scope can automatically cancel child coroutines if something goes wrong or if a user simply changes their mind and decides to.The scope is generally responsible for child coroutines, and their lifetime is attached to the lifetime of the scope.Let's see what benefits structured concurrency has over global scopes: The mechanism providing the structure of the coroutines is called structured concurrency. Starting a new coroutine from the global scope using GlobalScope.async or GlobalScope.launch will create a top-level " independent" coroutine. So it will consume some memory while your server application is running.Įven if your server app is finished running but process is not destroyed, a launched coroutine may still be running and consume the memory. When you first use of GlobalScope it will be loaded into the memory and stay there until one of the following happens: In Kotlin/JVM a static variable comes into existence when a class is loaded by the JVM and dies when the class is unloaded. GlobalScope.launch Īn object represents a single static instance(Singleton). Here's an example: /* I don't know Kafka, but let's pretend this function gets In your case, scoping them to the processing of a single message seems appropriate. Your coroutines can leak if you don't do this. You should scope your concurrency appropriately using structured concurrency.
0 Comments
Leave a Reply. |