Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

java - Is REST controller multithreaded?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...