How to send immediately a HTTP-response and do further processing afterwards in Spring Boot?
My code:
@Configuration
@EnableAsync
public class Application Configuration {
....
}
then a function in my Service which is long running and should be executed asynchronously
@Service
public class MyService {
@Async
public void executeDBUpdate() {
...log.info(Thread.getCurrentThread.getName());
}
}
and my Controller:
@PostMapping("/update")
@ResponseStatus(HttpStatus.ACCEPTED)
public ResponseEntity<String> updateDB() {
...
log.info(Thread.getCurrentThread.getName());
ComparableFuture.runAsync(() - > myservice.executeDBUpdate());
return new ResponseEntity<>(HttpStatus.ACCEPTED);
I would expect that HttpStatus.ACCEPTED is send immediately and executeDBUpdate is running in separate Thread still further. Looking at thread name in fact I see different threads, so a new thread is used for executeDBUpdate.
But the HttpStatus.ACCEPTED is not send immediately, but only after the AsyncTask is done, even if in Debugger I see that updateDB() is processed immediately further
Is thee any way to send response immediately?
runAsyncas the method is already@Asyncso you can just call the method on the service. You are now using 2 threads where you would use 1 otherwise (or actually 3 instead of 2).