In common way, if the java webserver wants to serve (Jetty, ...) for multiple requests, the server has to open a thread for each request. And if you have a large amount of requests, you have to put the thread into a pool to keep the server works without dead. The disadvantage of this way is the server consumes a lot of resource and the client have to wait in the queue of the thread pool.
So some newer versions of Jetty support Asynchronous Servlet, that allow server saves the information of all request without keeping the threads wait for the event to send back the response to client. You can find out at this link
I have some lines of code:
public class AsyncServlet extends HttpServlet implements OnEventCome {
List<AsyncContext> listContext = new ArrayList<>();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
AsyncContext ctxt = req.startAsync();
ctxt.setTimeout(3600000l);
synchronized (listContext) {
listContext.add(ctxt);
}
}
@Override
public void onEventCome() {
synchronized (listContext) {
for (AsyncContext ctxt: listContext) {
ctxt.start(new Runnable() {
@Override
public void run() {
ctxt.complete();
}
});
}
listContext.clear();
}
}
}
The function doPost
gets client's request information and finish immediately. Event onEventCome
will wait for an event to send all responses to all clients.
My question is: How can the servlet can make all clients keep connection and wait for response without open any threads?