Cory Klein Cory Klein - 6 months ago 12
Java Question

Send Spring response stream immediately rather than wait until method return

I have a request mapping that looks like this:

private final static byte[] byteArray = ...;

@RequestMapping(value=Array("/foobar"))
void sendByteArray(@RequestBody Request request, OutputStream os) {
os.write(byteArray);
os.flush();
doLengthyCleanup();
}


I'm finding that the request client does not actually receive the response body until after the service has completed
doLengthyCleanup()
.

Since the cleanup doesn't affect the response itself, I'd like to improve my response time by performing the cleanup after sending the response. How can I do this?

Answer
@RequestMapping(value=Array("/foobar"))
void sendByteArray(@RequestBody Request request, OutputStream os) {
  os.write(byteArray);
  os.flush(); // not sure
  doLengthyCleanup(); 
}

@Async
void doLengthyCleanup() {
  // this will be executed asynchronously
}