Java - 如果进程挂起,我应该如何检测/终止进程(以前使用的看门狗/超时观察器)

时间:2013-03-21 14:47:53

标签: java multithreading process timeout watchdog

我正在更新一些旧代码,并且不确定下面复制Watchdog / TimeoutObserver功能的最佳方法。但是,这是一种老式的方式,我正在尝试将其更新为更符合jre7。任何建议或帮助将不胜感激。

import org.pache.tools.ant.util.Watchdog;
import org.pache.tools.ant.util.TimeoutObserver;


 public class executer implemnts TimeoutObserver {

     public String execute() throws Exception {
         Watchdog watchDog = null;

         try { 
                    //instantiate a new watch dog to kill the process
        //if exceeds beyond the time 
        watchDog = new Watchdog(getTimeout());
        watchDog.addTimeoutObserver(this);
        watchDog.start();

                 ... Code to do the execution .....

              } finally {
             if (aWatchDog != null) {
                  aWatchDog.stop();
             }
         } 
         public void timeoutOccured(Watchdog arg0) {
              killedByTimeout = true;

              if (process != null){
                   process.destroy();
              }
              arg0.stop();
        }

      }

1 个答案:

答案 0 :(得分:0)

您可以使用Future.cancel(boolean)方法让任务异步运行一段时间。为了使其正常工作,您的Runnable应使用Thread.currentThread().isInterrupted()检测线程中断状态(这是代码似乎位于process.destroy()内)。

下面是 Java Concurrency in Practice 一书的示例(第7章“取消”)。有关此任务的其他解决方案,请参阅本书。

public static void timedRun(Runnable r, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException {
    Future<?> task = taskExec.submit(r);
    try {
        task.get(timeout, unit);
    } catch (TimeoutException e) {
        // task will be cancelled below
    } finally {
        // Harmless if task already completed
        task.cancel(true); // interrupt if running
    }
}