Search code examples
javatomcatcatalina

How to prevent service from starting until after Catalina has started


I have a JAX-WS client that I am running on Apache Tomcat 9. The client polls for data by entering an infinite loop and is set up as a servlet to load on startup. The issue I am having is that the servlet starts and enters the loop before Catalina is finished starting up.

I have tried using sleep() and wait() to no avail, I have tried implementing org.apache.catalina.LifecycleListener and this hasn't worked either.

Here is my servlet class:

@WebServlet("/MyClient")
public class MyServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    public void init() throws ServletException {
        System.out.println("Servlet Started");
        MyClient client = new MyClient();
        client.startClient();

    }
}

Here is my polling class:

public class Polling {

    private static final int TWO_MINUTES = 120000;

    public void startPoll() throws IOException {
        for (;;) {
            //Do something
            try {
                Thread.sleep(TWO_MINUTES);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}

I am expecting to see org.apache.catalina.startup.Catalina.start Server startup in XXXX ms before my program prints "Servlet Started" however it is starting the servlet first which makes tomcat hang and prevent access to other web apps.


Solution

  • You won't see Server startup, because you highjacked the initializing thread and started to do polling with it. The server would be started after your servlet is initialized, but it never finishes initializing since you call startPoll() in init() and it never returns.

    Instead of hand-crafted polling with an infinite loop and manual 2 minute sleep, look into scheduling, for example with Quartz or at least a ScheduledExecutorService, here's a Tomcat based example.