I had a similar problem. I have some Java programs that are basically long-running daemon processes. It's nice to be able to stop them and bounce (restart).
I used two approaches. Both have advantages and disadvantages. One of them is to configure the signal handler by placing such a function in some class of your program (in my case, it is in the class with the main method).
import sun.misc.Signal; import sun.misc.SignalHandler; ... private static boolean stopNow = false; private static boolean restartNow = false; ... private static void handleSignals() { try { Signal.handle(new Signal("TERM"), new SignalHandler() { // Signal handler method for CTRL-C and simple kill command. public void handle(Signal signal) { MyClass.stopNow = true; } }); } catch (final IllegalArgumentException e) { logger.warn("No SIGTERM handling in this instance."); } try { Signal.handle(new Signal("INT"), new SignalHandler() { // Signal handler method for kill -INT command public void handle(Signal signal) { MyClass.stopNow = true; } }); } catch (final IllegalArgumentException e) { logger.debug("No SIGINT handling in this instance."); } try { Signal.handle(new Signal("HUP"), new SignalHandler() { // Signal handler method for kill -HUP command public void handle(Signal signal) { MyClass.restartNow = true; } }); } catch (final IllegalArgumentException e) { logger.warn("No SIGHUP handling in this instance."); } }
It works solidly for us in production. For this you need a real Sun JRE; the one that comes with a typical Linux distribution does not contain a signal. It also works fine on Windows, but you are not getting a HUP signal. To run this thing you need a shortcut or shellscript.
Also, keep in mind that signal processing is a big bold notch. Do not try to do too much inside your signal handler. You can see that my sample code just sets static flags. Other parts of my program find that the flag is changed and turned off. I could experiment with more complex code inside the signal handler, but I did not want to take the burden of QA.
Another approach is to structure your program as a servlet. You will write a class that extends the HttpServlet in this case. Override Servlet.init with a method that starts your workflow. Similarly, override Servlet.destroy with a method that disables.
You can then use a Java EE container container, such as Tomcat, to control starting and stopping.
source share