Asynchronous task from Java servlet

I need to perform an asynchronous task when the endpoint of a RESTful web service is called. In fact, the endpoint is prompted to do the POST operation. It should immediately return 200 OK to the caller, create a thread, and complete its resource-intensive task. Upon completion, the stream will then POST to the appropriate endpoint on the caller (another REST server), indicating success (passing a token representing the initial transaction request).

What are the best methods to perform asynchronous actions inside a servlet that I should be aware of?

+7
source share
4 answers

Servlet 3.0 supports asynchronous operations . Tomcat 7.0 is already stable, so you can get it and try new features.

If you do not need to output data continuously, but to easily start the background process, you can use any available asynchronous mechanism:

+8
source

Besides the complexity of asynchronous coding in Java, another “best practice” in RESTful web services is to use HTTP status codes to describe the response to the server as much as possible. If you have no good reason to stick to 200 (i.e. a client you cannot change is expecting this), you should return HTTP 202 :

202 Accepted

The request has been accepted for processing, but processing is not completed.

+4
source

The only advice for your scenario would be to use a thread pool, rather than creating a new thread for each request. In Java, it is very simple, just create a pool once during application launch (see the Executors class) and send new tasks to it every time you need to perform some asynchronous operation. For your scenario, these tasks will perform resource-intensive operations and a second REST call from another thread, after the original request was sent from 200.

+1
source

In the Java EE container, it is recommended that you use the WorkManager API (JSR-237). Check out this article for a review.

A J2EE container can serve multiple users at the same time (in parallel) by managing a thread pool, but for various reasons, opening independent threads in a single J2EE container is not recommended. Some containers, security managers will not allow the user of the program to open streams. Moreover, if some containers were allowed to open threads, then they won’t deal with these topics and, therefore, there are no container-managed services that will be available for flows.

0
source

All Articles