Asynchronous task from Java servlet
I need to perform an 开发者_开发问答asynchronous task when a RESTful web service endpoint is called. Effectively, the endpoint is asked to perform a body of work with a POST operation. It should immediately return a 200 OK to the caller, spawn a thread and perform it's resource intensive task. On completion, the thread would then POST to a corresponding endpoint on the caller (another REST server) indicating success (passing a token that represents the initial transaction request).
What are the best practice approaches for performing asynchronous actions inside a servlet that I should be aware of?
Servlet 3.0 has support for asynchronous operations. Tomcat 7.0 is already stable, so you can get it and try the new features.
If you don't need to output data continously, but to simply start a background process, then you can use any asynchronous mechanism available:
- Executors framework
new Thread(new Runnable())
@Async
(spring/ejb)
Aside from the complexities of async coding in Java, another "best practice" in RESTful web services is to use HTTP status codes to describe your server's response as accurately as possible. Unless you have a compelling reason to stick with 200 (ie a client which you can't change expects this), you should return HTTP 202:
202 Accepted
The request has been accepted for processing, but the processing has not been completed.
The only advice for your scenario would be to use thread pool rather than creating a new thread per request. In Java it is very easy, just create pool once during application startup (look at Executors class) and submit new tasks to it each time you need to perform some asynchronous operation. For your scenario this tasks will perform resource intensive operations and second REST call from within a different thread, long after the original request was served with 200.
In a Java EE container, the recommended way is to use the WorkManager API (JSR-237). Check this article for an overview.
A J2EE container can serve multiple users at the same time (in parallel) by managing a pool of threads, but for various reasons opening independent threads within a single J2EE container is not recommended. Some containers' security managers will not allow user programs to open threads. Moreover, if some containers allowed opening threads, then they would not manage those threads and therefore no container-managed services would be available for the threads.
精彩评论