I've been doing this tutorial about how to return async callable object. It works as intended. But while the first request sleeps for 5 seconds I get the second request, controller waits for the previous request to finnish before handling the second one.
How to make controller handle immediately every request and make sleeping in a background?
@Edit
Example: Imagine a situation, that my controller needs to make a request to external api and based on its response it should send his own response. External api call takes lets say 2 seconds. I want users of my application to wait only that 2,5 seconds and not be placed in queue, because the controller can handle only one request at a time.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With