2013-03-21 45 views
0

我在更新一些舊代碼的過程中,我不確定複製下面的Watchdog/TimeoutObserver功能的最佳方式。然而,這是一種老式的做法,我正試圖將其更新爲更符合jre7標準。任何意見或幫助將不勝感激。Java - 我應該如何檢測/終止一個進程,如果它掛起(以前使用看門狗/ timeoutobserver)

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(); 
     } 

     } 
+0

你可以把WatchDog的代碼? – 2013-03-21 15:13:35

回答

0

您可以使用Future.cancel(boolean)方法讓任務運行的異步一定的時間。要使其工作,您的Runnable應該使用Thread.currentThread().isInterrupted()(這是代碼似乎在您的process.destroy()中)檢測到線程中斷狀態。

以下是Java併發實踐書(第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 
    } 
} 
相關問題