简体   繁体   English

正常停止正在运行的Java程序

[英]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. 我一直在寻找一种将命令发送到正在运行的Java程序的方法,但是大多数帖子建议实现listener或使用Jetty (或其他服务器)实现包装程序。

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. 场景是,我有一个Java程序,它将无限期运行,并且将产生一些正在运行的线程。 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. 该程序在linux环境中运行。

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. 谢谢你的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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