2

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?

1
  • You don't need runAsync as the method is already @Async so 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). Commented Aug 31, 2023 at 11:19

1 Answer 1

2

OK, solved it. It works as designed, however not if you set Breakpoint in the application. If you debug and have breakpoints, processing is stopped here and response sending after leaving debugger.

Using Thread.sleep I see desired response

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.