7

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.

matt b
  • 138,234
  • 66
  • 282
  • 345
Anton Kazennikov
  • 3,574
  • 5
  • 30
  • 38
  • 3
    How ironic that the first google result is a question on this site that answers your question: http://stackoverflow.com/questions/4650713/jetty-stopping-programatically-causes-1-threads-could-not-be-stopped – Jeff Swensen Apr 19 '11 at 15:55
  • 1
    How is it started? Please provide a bit more information on environment and you will get better answers – Kennet Apr 19 '11 at 15:55
  • 1
    Ironic, yes. But it isn't a clean solution. Using this solution I need to find a correct sleep time before calling server.stop(). – Anton Kazennikov Apr 19 '11 at 16:04
  • 5
    How ironic is it that *this* question is now the first google search result for ?q=programmatically+stop+jetty+server – Dexygen Jun 10 '13 at 22:37

3 Answers3

6

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.

Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
James Anderson
  • 27,109
  • 7
  • 50
  • 78
2

Try server.setGracefulShutdown(stands_for_milliseconds);.

I think it's similar to thread.join(stands_for_milliseconds);.

DarthJDG
  • 16,511
  • 11
  • 49
  • 56
Sven
  • 21
  • 2
1

Having the ability for a Jetty server to be shutdown remotely through a HTTP request is not recommended as it provides as potential security threat. In most cases it should be sufficient to SSH to the hosting server and run an appropriate command there to shutdown a respective instance of a Jetty server.

The basic idea is to start a separate thread as part of Jetty startup code (so there is no need to sleep as required in one of mentioned in the comment answers) that would serve as a service thread to handle shutdown requests. In this thread, a ServerSocket could be bound to localhost and a designated port, and when an expected message is received it would call server.stop().

This blog post provides a detailed discussion using the above approach.

01es
  • 5,362
  • 1
  • 31
  • 40