Akhil K Nambiar
Akhil K Nambiar

Reputation: 3975

Async process in Spring

I have the following in my Controller

@RequestMapping("/")
@ResponseBody
public String index() {
    System.out.println("Parent: " + Thread.currentThread().getName());
    task();
    return "Hello";
}

@Async("executorWithPoolSizeRange")
public void task() {
    try {
        System.out.println("Child Process: "
                + Thread.currentThread().getName());
        System.out.println("................................. started");
        Thread.sleep(5000);
        System.out.println("................................. done");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

I have also added

    <task:annotation-driven executor="executorWithPoolSizeRange" />
<task:executor id="executorWithPoolSizeRange" pool-size="5-25"
    queue-capacity="100"></task:executor>

to my mvc-dispatcher-servlet.xml. Am I still missing out something? The process is not working asynchronously. The controller takes 5 secs to return response and both the output of thread names is same. That is its the same thread. (I know I shouldn't rely on thread name since its automatically set).

Upvotes: 0

Views: 1249

Answers (2)

Akhilesh
Akhilesh

Reputation: 1410

Have you tried BlockingQueue yet.It will ease your asynchronous task and is based on producer consumer approach , where consumer will do your task asynchronously. See this link for more info.

Upvotes: 0

rcgeorge23
rcgeorge23

Reputation: 3694

I think the reason your method invocation is not asynchronous is because you are invoking the method within the same component. The async proxy for your method that spring creates is only seen by other services making an 'external' call to your task() method.

Try moving your task() method out of the controller and into a service. Then when you invoke the method from your controller you should be invoking the 'async' version.

Upvotes: 3

Related Questions