I get some of the idea of async services, but haven't coded many, so the mechanics especially in Java are new to me. Basically, I have a long running service that I want to fork off to another thread and be able to check in on the status of it using a different service. For now, I can get the work started, I don't have a way to check in on it yet. But worse:
In the POST service asyncUploadSoftLayerFile
below:
@RestController
@RequestMapping("/")
public class MyController {
...
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/async-files")
public DeferredResult<ResponseEntity<JobExecutionResult>> asyncUploadSoftLayerFile(@RequestParam MultipartFile file) throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, IOException, JobExecutionAlreadyRunningException{
logger.info("Received async-CompleteableFuture request");
DeferredResult<ResponseEntity<JobExecutionResult>> output = new DeferredResult<ResponseEntity<JobExecutionResult>>();
ForkJoinPool.commonPool().submit(() -> {
logger.info("Processing in separate thread: Thread-ID="+Thread.currentThread().getId());
JobExecutionResult jobExecutionResult = null;
try {
myReallyLongRunningProcess();
} catch (JobParametersInvalidException | JobExecutionAlreadyRunningException | JobRestartException
| JobInstanceAlreadyCompleteException | IOException e) {
logger.error("Error processing /async-files upload in Thread-ID: "+Thread.currentThread().getId(),e);
throw new RuntimeException(e);
}
if (!"COMPLETED".equals(jobExecutionResult.getExitStatus())) {
throw new UploadFileException(file.getOriginalFilename() + " exit status: " + jobExecutionResult.getExitStatus());
}
ResponseEntity<JobExecutionResult> responseEntity = ResponseEntity.ok(jobExecutionResult);
output.setResult(responseEntity);
});
return output;
}
}
Spring does do it's deferred thing, and I can see it spawned the work off to another thread. But it did not return back to the caller. Instead I saw:
2021-07-27 05:20:00 DEBUG o.s.web.servlet.DispatcherServlet - Exiting but response remains open for further handling
So it only partially gave me what I wanted. How can I get Spring to spawn the work off to another thread, (and ideally be able to refer to that process by another web service call), but immediately return some sort of response to the web browser?
This is part of an effort to start work but track the percentage complete as it goes along.