The scenario I am trying to complete is the following:
- The client submits a HTTP POST request to the servlet.
- The servlet sends a response to the client confirming the request has been received.
- The servlet then sends an email notification to the system administrator.
So far I am able to complete the following steps in the order described above, however I run into an issue at the end. If the client makes another HTTP request to the same or another servlet while the email notification method EmailUtility.sendNotificationEmail()
is still running, the servlet will not run any further code until this email method is completed (I am using javax.mail
to send emails if that matters).
I have tried to use AsyncContext
to get around this (which I may be using incorrectly), but unfortunately the issue still remains.
How can I make the EmailUtility.sendNotificationEmail()
run in a different thread/asynchronously so that the servlets do not have to wait for this method to complete?
This is my code so far:
//Step 1: Client submits POST request to servlet.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
//Step 2: Servlet sends response to client.
response.getWriter().write("Your request has been received");
response.getOutputStream().flush();
response.getOutputStream().close();
//Step 3: Servlet send email notification.
final AsyncContext acontext = request.startAsync();
acontext.start(new Runnable() {
public void run() {
EmailUtility.sendNotificationEmail();
acontext.complete();
}
});
}