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?
Asynchronous programming in Java is a technique for parallel programming that lets teams distribute work and build application features separately from the primary application thread. Then, when the team is ready with the feature, the code is synced with the main thread.
An asynchronous process is a process or function that executes a task "in the background" without the user having to wait for the task to finish.
An AsyncContext is created and initialized by a call to ServletRequest#startAsync() or ServletRequest#startAsync(ServletRequest, ServletResponse) . Repeated invocations of these methods will return the same AsyncContext instance, reinitialized as appropriate.
The web container calls the destroy method when it needs to remove the servlet such as at time of stopping server or undeploying the project.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With