Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Async task runs synchronously

I'd like to implement an asynchronous task, and a page which returns immediately and starts the task in the background. However, the page instead waits for the background task to complete and returns only afterwards. When I visit /start it takes 15s to load the page. I'm using Spring 3.2.0. I have a line containing <task:annotation-driven/> in my test-servlet.xml.

The odd thing is that even if I replace @Async with @Async("this_bean_does_not_exist"), the application does the same(though I would be expecting an exception for referencing a not existing bean).

public interface AsyncTestService {
    void startSlowProcess();
}

@Service
public class AsyncTestServiceImpl implements AsyncTestService {

    @Override
    @Async
    public void startSlowProcess() {
        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

@Controller
public class TestController {

    @Autowired
    AsyncTestService asyncTestService;

    @RequestMapping("/start")
    @ResponseBody
    public String startSlowProcess() {
        asyncTestService.startSlowProcess(); // It takes 15s to complete
        return "STARTED"; // should return immediately
    }
}
like image 726
David Frank Avatar asked Aug 13 '26 05:08

David Frank


1 Answers

You probably need an executor. Try this:

<task:annotation-driven executor="myExecutor" />    
<task:executor id="myExecutor" pool-size="5"/>

EDIT: Another possible solution: use EnableAsync instead (available since Spring 3.1)

like image 199
Szymon Jednac Avatar answered Aug 14 '26 17:08

Szymon Jednac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!