First of all, I want to say that English is not my first language, so excuse me if I make some obvious mistakes or something is not entirely clear. Question:
I was recently transferred to a new project where we are developing a Java EE application that provides some REST services through Jersey + Hibernate. Before that, I had only experience with Java SE, but someone had already laid the foundation, so I had time to learn from its code and use Google and much more.
The fact is that among those REST services there is one that can take a lot of time, and the team decided to implement it in a non-blocking way. We will define two services: the first client will send the data for processing, then we will return the confirmation and begin processing, while the client can continue other actions; and the second allows the client to check later if their work is completed.
Studying how to implement this in the best way, my aforementioned colleague discovered a function AsyncServletfor Servlets 3.0 and had a proof of concept implemented before my arrival, which later turned into a locally working (but very dirty) version of the service. He says that for this he had to quit Jersey because Servlets 3.0 were not compatible with the version of Jersey we are working with, and finally decided to implement a simple servlet.
In the end, he got something like this (I don’t have the code right now, since I am at home and write from memory, but I will try to write it as clear as possible and try to fix any big mistakes tomorrow morning):
A servlet that processes new requests in doPost()and validation doGet():
@WebServlet(asyncSupported = true)
void doGet(HttpServletRequest req, HttpServletResponse res) {
}
void doPost(HttpServletRequest req, HttpServletResponse res) {
AsyncContext ctx = req.startAsync(req, res);
ctx.start(new WorkerThread(ctx, someOtherDataFromRequest);
}
Both the workflow that implements Runnableand the first thing it does is call ctx.complete()in AsyncContext, which was sent to it in the constructor. My colleague’s opinion is that if the employee notifies the parent immediately after its completion, the parent can send the response to the client and then start its own processing with other data passed to it in the constructor:
public class WorkerThread implements Runnable {
public WorkerThread(AsyncContext ctx, SomeOtherData data){
}
public void run() {
ctx.complete();
}
}
, , (Tomcat 7), , JBoss EAP 6.1, , . , ( , , , , , ...)
, , - async , . , 10 , ; Tomcat , 10s ; JBoss 10 , .
AsyncServlet, , , , , , , , Tomcat. javadocs complete() , JBoss :
, - , startAsync, , ( AsyncListener # onComplete (AsyncEvent) ) , .
, , AsyncServlet , , ( , ). , , ...