I’m trying to confirm if my understanding of coroutines is correct.
Given that: methodThatContainsBlockingCode(i) calls some sort of blocking code, be it jdbc, REST call, etc…
Then 10 lightweight threads will be created and block execution till the last one completes
// methodThatContainsBlockingCode(i) is a 'mocked' function that calls Thread.sleep(3_000)
suspend fun process() : Unit {
withContext(Dispatchers.IO) {
for (i in 1 .. 10) {
async() { methodThatContainsBlockingCode(i) }
}
}
}
When I see the code execute it takes like 3 to 4 seconds total for them to complete foo() to return the calling function. This is great, as without the coroutine it would take > 30 seconds.
Some reading/videos/medium posts have lead me to believe that I’m going to have to wait for the methods in the coroutines to finish before the method returns? Is this correct?
Is there a way to immediately return where the code will continue to execute? The reason I’m asking is because foo() is being called from a Spring RestController and I would really like to immediately return to the client so the client does not have to wait. I’m dealing with legacy code here and refactoring to a reactive approach is not feasible.
FYI, I did get this to work w/ a CompletableFuture but it seems the completeOnTimeOut method doesn’t execute
fun foo(request: TheRequest) {
val ids = checkIds(request.ids)
ids.forEach {
this.log.info("Executing work with id: $it")
CompletableFuture.supplyAsync{
barService.execute(it)
}.thenAccept{ barService.logWorkComplete(it) }
//.completeOnTimeout(timeOutError(), 1, TimeUnit.HOURS)
}
}