2015-06-04 100 views
0

I用於在超時後中斷任務的ExecutorService。我爲此使用ScheduledExecutorService。首先,我提交了該線程,並立即開始並保留創建的未來。之後,我使用ScheduledExecutorService作爲一項新任務,在一段時間後取消保留的未來。ScheduledExecutorService和ThreadPoolTask​​Executor在超時後中斷任務

//Start Spring executor to submit tasks 
 
ThreadPoolTaskExecutor taskExecutor = (ThreadPoolTaskExecutor) ApplicationContextProvider.getApplicationContext().getBean("taskExecutor"); 
 

 
CompletionService completionService = new ExecutorCompletionService(taskExecutor); 
 
//End Spring executor to submit tasks 
 

 
// Start ScheduledExecutorService to submit returned future object to timeout 
 

 
ScheduledExecutorService executor = Executors.newScheduledThreadPool(Integer.parseInt(config.getProperty("DBPOLLER_COREPOOLSIZE"))); 
 

 
final Future<String> future = completionService.submit(batchJob); // Submit actual task and get future 
 

 
// submit future 
 

 
executor.schedule(new Runnable() { 
 
     public void run() { 
 
         future.cancel(true); 
 
     } 
 
    }, dbPollerTimeOut, TimeUnit.MINUTES); 
 

 
int count = taskExecutor.getActiveCount(); 
 

 
if (count == 0) { 
 

 
       taskExecutor.shutdown(); 
 
       executor.shutdown(); 
 
       finalExitStatus = 0;      
 
       break; 
 

 
      }

我已經實現瞭解決方案,它是在以下網址: ExecutorService that interrupts tasks after a timeout,它做工精細,直到超時,但一旦發生超時,這將取消所有enter code here任務我線程池是不能接受的。我只需要取消長時間運行並超時的任務。

任何想法如何實現這一目標?

+0

什麼是'batchJob'?取消它必須負責取消「所有'在這裏輸入代碼'任務[in] ThreadPool」。所以,顯示'batchJob'的代碼。 'batchJob'是否參考了很多其他任務?這將是一個問題。 – erickson

+0

請參閱[輸入鏈接說明](http://stackoverflow.com/questions/42946627/scheduledexecutorservice-that-interrupts-after-a-timeout) –

回答

0

目前尚不清楚您的CompletionService是什麼,並且您正在提交您的batchJob,因此很難確定問題的確切根本原因。但提交少量任務並在一段時間後取消它們的理想方案是使用ScheduledExecutorService來實現這兩個目的。

因此,可以嘗試提交ScheduledExecutorServiceexecutor的實例batchJob

final Future<String> future = executor.submit(batchJob); // Submit actual task and get future  

編輯更新:你應該在你的代碼
做重要改變我看到你永遠不會停止你的ScheduledExecutorService這是錯誤的,因爲它的資源佔用將永遠不會被釋放,直到你停止它。所以,你的更新代碼應該如下:

ScheduledExecutorService executor = Executors.newScheduledThreadPool(Integer.parseInt(config.getProperty("DBPOLLER_COREPOOLSIZE"))); 
final Future<String> future = executor.submit(batchJob); // Submit actual task and get future 
executor.schedule(new Runnable() { 
     public void run() { 
     future.cancel(true); 
     executor.shutdownNow(); 
     } 
    }, dbPollerTimeOut, TimeUnit.MINUTES); 
相關問題