Programmatic Jetty shutdown

Anton Kazennikov picture Anton Kazennikov · Apr 19, 2011 · Viewed 13.5k times · Source

How to programmatically shutdown embedded jetty server?

I start jetty server like this:

Server server = new Server(8090);
...
server.start();
server.join();

Now, I want to shut it down from a request, such as http://127.0.0.1:8090/shutdown How do I do it cleanly?

The commonly proposed solution is to create a thread and call server.stop() from this thread. But I possibly need a call to Thread.sleep() to ensure that the servlet has finished processing the shutdown request.

Answer

James Anderson picture James Anderson · Sep 5, 2013

I found a very clean neat method here

The magic code snippet is:-

        server.setStopTimeout(10000L);;
        try {
            new Thread() {
                @Override
                public void run() {
                    try {
                        context.stop();
                        server.stop();
                    } catch (Exception ex) {
                        System.out.println("Failed to stop Jetty");
                    }
                }
            }.start();

Because the shutdown is running from a separate thread, it does not trip up over itself.