Async method is not behaving asynchronously

I have written method which takes more time than I desire. It depends on external systems for response so it is slow. I don’t have much control over that. Because of that method I cannot wait for that period of time, so my requirement is that after I initialize that method and provided the parameters required it should run in background while the parent method which has called this time consuming method will finish it’s execution.

I have used @Async annotation of spring to declare the method as asynchronous. This particular method is being called from RestController which will finish it’s execution before this Asynchronous method will finish it’s execution.
I have declared custom executor and has mapped it in dispatcher-servlet.xml.

The method is executing asynchronously but the moment caller method finishes it’s execution, even though asynchronous method is still incomplete, stops executing abruptly.How can I achieve that the asynchronous method finishes it’s execution even though caller method finishes earlier. I cannot wait in caller method for asynchronous method to finish it’s execution.

Code Sample
@Service
class TimeConsumingService{

@Async("customExecutor")
    public  void  callTimeConsumingService( ){

//This call takes time between 50000 miliseconds to 70000 miliseconds
} 

}

//Caller Method

@RestController
@RequestMapping("rest/document/content")
public class CallerController
{

@Autowired
TimeConsumingService timeConsumingService;


 @LoggingAdvice
    @RequestMapping(value="/request", method = RequestMethod.POST )
    public String requestContent( @RequestParam(value = "file") MultipartFile file) throws Exception, IOException
    {

timeConsumingService.callTimeConsumingService();

}
}

Archive from: https://stackoverflow.com/questions/59063998/async-method-is-not-behaving-asynchronously

Share

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *