Programmatic Jetty shutdown
Solution 1
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.
Solution 2
Try server.setGracefulShutdown(stands_for_milliseconds);
.
I think it's similar to thread.join(stands_for_milliseconds);
.
Solution 3
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.
Anton Kazennikov
Updated on July 13, 2022Comments
-
Anton Kazennikov almost 2 years
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.
-
Jeff Swensen about 13 yearsHow ironic that the first google result is a question on this site that answers your question: stackoverflow.com/questions/4650713/…
-
Kennet about 13 yearsHow is it started? Please provide a bit more information on environment and you will get better answers
-
Anton Kazennikov about 13 yearsIronic, yes. But it isn't a clean solution. Using this solution I need to find a correct sleep time before calling server.stop().
-
Dexygen almost 11 yearsHow ironic is it that this question is now the first google search result for ?q=programmatically+stop+jetty+server
-