2015-10-08 62 views
2

我知道我可以拋出異常來抑制已計劃在ScheduledExecutorService中重複執行的任務的進一步執行(請參閱this question)。停止並從ScheduledExecutorService中刪除任務

我也知道我可以setRemoveOnCancelPolicy(true)來確保取消的任務從隊列中移除。

我的問題是:當我從它內部拋出一個異常時,這個任務是否真的從調度器中刪除?這是否通過隱性取消未來而發生?如果是的話,這是否意味着setRemoveOnCancelPolicy()也支持這種情況?

在Javadocs中找不到任何東西。

回答

1

我想知道同樣的東西,在文檔中找不到任何東西,所以我試了一下。觀察:

  • 投擲RuntimeException馬克作爲未來不取消
  • Runnable從調度程序的隊列中刪除,不管setRemoveOnCancelPolicy()

嘗試一下自己:

public class SchedulerTest { 
    protected final Logger log = LoggerFactory.getLogger(this.getClass()); 

    @Test 
    public void schedulerExecutionException() throws Exception { 
     log.info("Test: schedulerExecutionException"); 

     ScheduledThreadPoolExecutor sched = new ScheduledThreadPoolExecutor(2); 
     sched.setRemoveOnCancelPolicy(true); 

     ScheduledFuture future1 = sched.scheduleAtFixedRate(new Runnable() { 
      int counter = 0; 
      @Override 
      public void run() { 
       log.info("Runnable 1: "+ ++counter); 

       if (counter >= 2) { 
        log.info("Runnable 1: BOOOM"); 
        throw new RuntimeException("boom"); 
       } 

      } 
     }, 1, 1, TimeUnit.SECONDS); 

     ScheduledFuture future2 = sched.scheduleAtFixedRate(new Runnable() { 
      int counter = 0; 
      @Override 
      public void run() { 
       log.info("Runnable 2: "+ ++counter); 
      } 
     }, 1, 1, TimeUnit.SECONDS); 

     long cutoff = new Date().getTime() + 6000; 

     while (new Date().getTime() < cutoff) { 
      log.info("Scheduler Queue size: "+ sched.getQueue().size()); 
      log.info("Future 1: is "+ (future1.isCancelled() ? "" : "not ") +"cancelled, is "+ (future1.isDone()? "" : "not ") +"done"); 
      log.info("Future 2: is "+ (future2.isCancelled() ? "" : "not ") +"cancelled, is "+ (future2.isDone()? "" : "not ") +"done"); 
      Thread.sleep(1000); 
     } 
     assertEquals(sched.getQueue().size(), 1); 

     future2.cancel(true); 
     log.info("Scheduler Queue size: "+ sched.getQueue().size()); 
     log.info("Future 1: is "+ (future1.isCancelled() ? "" : "not ") +"cancelled, is "+ (future1.isDone()? "" : "not ") +"done"); 
     log.info("Future 2: is "+ (future2.isCancelled() ? "" : "not ") +"cancelled, is "+ (future2.isDone()? "" : "not ") +"done"); 

     assertEquals(sched.getQueue().size(), 0); 

     sched.shutdownNow(); 
    } 
} 
相關問題