1

I'd been googling around for a way for me to send in command to a running Java program, but most of the post suggested to implement listener or wrap the program with a Jetty (or other server) implementation.

Is there a way to do this without adding additional dependencies?

The scenario is, i have a Java program which will be running indefinitely, and which will spawn a few running threads. I would like to be able to run a script to stop it, when it needs to be shut down, somewhat like the shutdown script servers tend to have. This will allow me to handle the shutdown process in the program. The program runs in a linux environment.

Thank you.

Joakim Erdfelt
  • 46,896
  • 7
  • 86
  • 136
ipohfly
  • 1,959
  • 6
  • 30
  • 57
  • Do you mean programmatically or just from the consle – TameHog Mar 27 '15 at 02:30
  • You could use a `Socket` to communicate we the process, but this assumes the process is listening or maybe writing a value to a particular file which the process is monitoring... – MadProgrammer Mar 27 '15 at 02:33
  • 4
    This answer may help: http://stackoverflow.com/a/2922031/2164109 just implement a shutdown hook, and whenever you want to stop your process, just use the TERM signal: kill -TERM _java_proccess_id_ – morgano Mar 27 '15 at 02:34
  • Thanks for the link to shutdown hook, will look into it. – ipohfly Mar 27 '15 at 04:52
  • Get to know about JMX from this thread: http://stackoverflow.com/questions/191215/how-to-stop-java-process-gracefully anyone used it before? – ipohfly Mar 31 '15 at 10:04

1 Answers1

1

Implemented the shutdown hook and so far it looks good. The implementation codes:

final Thread mainThread = Thread.currentThread();
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    logger.info("Shut down detected. Setting isRunning to false.");

                    if(processors != null && !processors.isEmpty()){
                        for (Iterator<IProcessor> iterator = processors.iterator(); iterator.hasNext();) {
                            IProcessor iProcessor = (IProcessor) iterator.next();
                            iProcessor.setIsRunning(false);
                            try {
                                iProcessor.closeConnection();
                            } catch (SQLException e1) {
                                logger.error("Error closing connection",e1);
                            }
                        }
                    }
                    try {
                        mainThread.join();
                    } catch (InterruptedException e) {
                        logger.error("Error while joining mainthread to shutdown hook",e);
                    }
                }
            });

Thanks for the suggestion.

ipohfly
  • 1,959
  • 6
  • 30
  • 57