3

Can anyone tell me, how to do long running transactional task using spring DeferredResult ? went through a lot of tutorial available on net but neither documentation nor examples clear on non Rest based application, which doesn't need long polling but running the task at background and immediately returning the HTTP response and subsequent calls to the same controller method just return the result. With some assumption i have created like the following

private static final Map<String, DeferredResult<ModelAndView>> deferredResults = new ConcurrentHashMap<>();

@RequestMapping(value = "longRunning", method = RequestMethod.POST)
public DeferredResult<ModelAndView> longRunning(@ModelAttribute LongRunningJob longRunningJob) {
    String resultKey = longRunningJob.getKey();                
    DeferredResult<ModelAndView> result = deferredResults.get(resultKey);
    if (result == null ) {
        deferredResults.put(resultKey, result = new DeferredResult<ModelAndView>());
        new Thread(runLongRunning(longRunningJob, result)).start();
    }
    result.onCompletion(() -> {
        deferredResults.remove(resultKey);});
    return result;
}

public Runnable runLongRunning((LongRunningJob newLongRunningJob, DeferredResult deferredResult) {
    return () -> {
        LongRunningJob returnJobValue = this.longRunningJobService.startLongRunningJob(newLongRunningJob); //startLongRunningJob is a transactional method
        ModelMap modelMap = new ModelMap();
        modelMap.put("returnJobValue", returnJobValue);
        modelMap.put("message", "Success");
        deferredResult.setResult(new ModelAndView("job-view", modelMap));
    };
}

Will it work or is there any other better way to handle it ? Will it be threadsafe is there any chances of getting into a race condition ?

Sreekanth
  • 539
  • 1
  • 7
  • 24

0 Answers0