在java中使用addShutdownHook

时间:2014-08-14 08:05:12

标签: java

我想按顺序执行以下操作

  • 1.停止jetty服务器
  • 2.从jetty删除已使用的资源
  • 3.重新启动jetty服务器。
  • 我在java中使用shutdownhook完成了以上操作:

    <code>
    
            Thread restartThread = new Thread(){
                public void run(){
                    try {
                        sleep(5000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    String osName = System.getProperty("os.name");
                    logger.debug("OS name:" + osName);
                    if (osName != null
                            && osName.toUpperCase().startsWith("WINDOWS")) {
                        Runtime.getRuntime().addShutdownHook(new Thread() {
                            public void run() {
                                try {
                                    List<String> cmdLine = new ArrayList<String>();
                                    cmdLine.add("cmd.exe");
                                    cmdLine.add("/C");
                                    cmdLine.add("start");
                                    cmdLine.add("\"\"");
                                    cmdLine.add(getBaseDir() + File.separator + "restart.bat");
    
                                    final ProcessBuilder pb = new ProcessBuilder(cmdLine);
                                    Process process = pb.start();
    
                                  if (process.exitValue() == 0) {
                                            // after stopping server delete stores
                                            deleteCertificates();
    
                                            // restores files
                                            restoreFiles(tmpdir, backupfilelist);
                                        } 
    
                                    //p.waitFor();
                                } catch (IOException e) {
                                    logger.error("Failed to restart:" + e.getMessage(), e);
                                } 
                            }
                        });
                        System.exit(0);
                    } else {
                        try {
                            Runtime.getRuntime().exec("service appservice restart");
                        } catch (IOException e) {
                            logger.error("Failed to restart:" + e.getMessage(), e);
                        }
                    }
                }
            };
            restartThread.start();
    <code>
    

    我担心的是它会按顺序执行,否则应用程序将无法恢复。

    0 个答案:

    没有答案