Is the REST controller multithreaded?

I did this tutorial on how to return an async called object. He works as intended. But , while the first request sleeps for 5 seconds, I get the second request, the controller waits for the previous request to be Finnish before processing the second.

How to make the controller process every request at once and do sleeping in the background?

@Edit

Example: Imagine a situation when my dispatcher has to make a request for an external api and based on his answer he has to send his own answer. An external api call allows you to talk for 2 seconds. I want the users of my application to wait only 2.5 seconds and not be queued, because the controller can only process one request at a time.

+1
source share
2 answers

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";//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

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 .

+4
source

What you want to do is what should be done in the first example of a related tutorial:

 @RequestMapping(value = "/block", method = RequestMethod.GET, produces = "text/html") public String executeSlowTask() { logger.info("Request received"); Thread.sleep(5000); logger.info("Servlet thread released"); return result; } 

This blocks the calling thread and waits until it is executed. If you call from another HTTP session, it will be a different thread, so this will be a new 5 second wait (not affected first).

Topics are related to HTTP calls while there are threads in the pool (tomcat server configuration).

This is not the case when the controller will block all subsequent calls during busy hours. It is multithreaded.

0
source

Source: https://habr.com/ru/post/1271805/


All Articles