Is REST controller multithreaded?
REST controller is multithreaded as the DisptcherServlet
handles multiple requests from the clients concurrently and serves using the respective controller methods. You can refer the request handling flow here
How to make controller handle immediately every request and make
sleeping in a background?
You can do that by returning 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";//Send the result back to View Return.jsp
} catch(InterruptedException iexe) {
//log exception
return "ReturnFail";
}};
return asyncTask;
}
Output:
WAITING STARTED: Thu Nov 24 21:03:12 GMT 2016
WAITING COMPLETED: Thu Nov 24 21:03:17 GMT 2016
After this, the view will be returned "Return.jsp" page.
Here, the controller method will be running in a separate thread (releasing the actual servlet thread) and once the task is completed the Result will be sent back again to the client (View etc..).
P.S.: You need to add @EnableAsync
as part of your application configuration, you can look here on this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…