Is a REST controller multithreaded?
The REST controller is multithreaded because the DisptcherServlet simultaneously processes several requests from clients and serves using the appropriate controller methods. You can link to the request flow here
How to make the controller process every request at once and make it sleep in the background?
This can be done by returning a Callable<String> in the Spring controller method, as shown below:
@Controller public class MyController { @RequestMapping(value="/sleep") public Callable<String> myControllerMethod() { Callable<String> asyncTask = () -> { try { System.out.println(" WAITING STARTED:"+new Date()); Thread.sleep(5000); System.out.println(" WAITING COMPLETED:"+new Date()); return "Return";
Output:
WAITING STARTED: Thu Nov 24 21:03:12 GMT 2016
WAIT COMPLETED: Thu Nov 24 21:03:17 GMT 2016
After that, the page "Return.jsp" will appear in the view.
Here, the controller method will be launched in a separate thread (releasing the real servlet thread), and as soon as the task is completed, the result will be sent back to the client (view, etc.).
PS: You need to add @EnableAsync as part of the configuration of your application , you can see it here .
source share