You are currently viewing Best practices Coroutine Scope for Spring Components

Best practices Coroutine Scope for Spring Components


I’m trying to figure out how to handle CoroutineScope in Spring managed beans. What I want to do is to use coroutines internally in a component.

Maybe I want to launch a coroutine doing some task and just return to caller. Or do some async operations and combining in some context. Or simply call other services that offer suspending functions.

Currently I have some outside code that expects a Java CompletableFuture. I compute this using a bunch of chained thenApply, thenCombine etc which is a nightmare to read and maintain. I’m looking to rewrite it using coroutines. (I’m familiar with future coroutine builder, but it still needs a scope!)

I understand that using GlobalScope or creating a scope on the fly via CoroutineScope is advised against since it works against structured concurrency

From the very limited information there is to find about this, I’ve seen someone suggest that the component itself implements CoroutineScope, and a reference to a parent job is kept, which can then be cancelled during spring destruction.

Is that a good approach? Any other alternatives or best practices? Or should coroutines not even be used in this manner at all?

submitted by /u/FederalSignature
[link] [comments]