0

I'm writing Java application and I want it can be shut down from the outside (I mean by bash script, or python, or something else).

But simply killing the application is not quite appropriate. This is because I have many running thread some of them are performing I/O and killing may lead written data to be in inconsistent state. So I want some sort of graceful shutdown. What I found is this:

import sun.misc.Signal;
import sun.misc.SignalHandler;

Signal.handle(new Signal("KILL"), new SignalHandler() {
        public void handle(Signal sig) {
            //Interrupt all threads and shutdown all services gracefully
        }
    });

But this is from sun.misc package and is not a public API. Is there a more appropriate way to gracefully shutdown Java application?

Some Name
  • 8,555
  • 5
  • 27
  • 77
  • If you have many running threads, you should be using an Executor and use the `shutdown()` method on the executor to stop them. Wait on all of your Executors to finish then exit. – markspace Apr 11 '18 at 20:38
  • If you need to force a shutdown, use the executor method `shutdownNow()` to interrupt all your threads. You'll have to write the individual tasks so that they recognize an interrupt as a request to exit. See Brian Goetz's [*Java Concurrency in Practice*](http://jcip.net/) – markspace Apr 11 '18 at 20:40
  • 1
    How about using shutdown hooks? This may very work nicely for your case (that is gracefully interrupting threads etc etc) https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread) – akortex Apr 11 '18 at 20:40
  • @markspace Sure, shutdown for all services is performed. But I was asking about how to shutdown JVM gracefully from another process? – Some Name Apr 11 '18 at 20:41
  • @Aris Sounds good! So If JVM receives `SIGKILL` it executes shutdown hook first? – Some Name Apr 11 '18 at 20:42
  • AFAIK, there basically isn't one. Listen on a "well known" named pipe for commands to shutdown the app, if you must. You'll need to make a little console app that sends commands to the pipe. – markspace Apr 11 '18 at 20:42
  • The docs that Aris linked to says that shutdown hooks are not guaranteed to be run if the JVM receives a SIGKILL. – markspace Apr 11 '18 at 20:46
  • @markspace `in response to a user interrupt, such as typing ^C` isn't it `SIGKILL`? So the only reliable way is to use `SignalHandler`? – Some Name Apr 11 '18 at 20:50
  • `SIGKILL` is the name of the signal that *no-one* can catch, so whether you use shutdown hooks or `SignalHandler` doesn’t matter, neither will work. When shutting down in response to `SIGTERM` or `SIGINT`, the shutdown hooks will be executed. In other words, install a shutdown hook, don’t mess around with `sun.misc.Signal` and it will work when pressing `ctrl+c` or executing `kill` (unless using `-9` resp. `-SIGKILL`). – Holger Apr 12 '18 at 15:36

0 Answers0