简体   繁体   中英

Stopping a running java program gracefully

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM