I am using Tomcat 9.0 to run Java code on some data from a database. I have a single servlet that is invoked by directly accessing x.x.x.x:8080/myapp/myservlet. The length of time to complete is between 5 seconds - 1 minute.
The servlet returns a response right away, leaving it to continue processing in the background. I am not sure Tomcat is supposed to be used like this. The problem is until the processing has actually finished, the web client cannot access x.x.x.x:8080/myapp/myservlet.
Each new web client can connect and invoke the servlet fine.
I simply want to invoke my java code as a background process in a fire and forget manner. Is this possible with Tomcat?
Any guidance would be great
CodePudding user response:
Move you code in a Thread or an executor and use the servlet only to start and monitor the execution.
public class myservlet extends HttpServlet
{
...
Thread t = null;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
if(t == null || !t.isAlive())
{
t = new Thread(new Runner());
t.setDaemon(true);
t.start();
out.write("Process started.\n");
}
else
out.write("Process running...\n");
}
public static class Runner implements Runnable
{
public void run()
{
// put your code here
}
}
}