简体   繁体   中英

How to cancel all threads in tasks when one task returns invalid in Threadpool executor

I have arbitrary amount of tasks that I submit to a ThreadPoolExecutor. Each of these tasks returns a code whether or not the task is successful. What I'd like to happen is that the first task that returns a failure code will invalidate/cancel/interrupt all the other tasks, almost like short circuiting the whole thing to save time. If no tasks have failed, then all tasks will run. Assume that the tasks are designed to handle the interrupts gracefully

for(int i = 0; i < size; i++) {
  Future<?> future = executor.submit(new Runnable() {
    @Override
     public void run() {
         returnValue = performWork();
         if(returnValue == FAILED)
             // signal cancel other tasks??
     }  
   });

   futureTaskList.add(future);
}

I'm trying to think of a good design that would allow me to check on the returnValue and if it returns a failed value, to cancel work on the remaining tasks.

I can loop through all the futures and do a get() but this not what I want since it will block on that particular task until it finishes, but what if another task has already completed with a failed result?

What are the ways to accomplish this most efficiently?

Possible duplicate question: In Java, how do I wait for all tasks, but halt on first error? 可能的重复问题: 在Java中,我如何等待所有任务,但是在出现第一个错误时停止?

If you use a ThreadPoolExecutor , it offers a hook beforeExecute() . You can use that to check for an atomic flag (set by the failed task) to decide if you want to cancel the given Runnable . Haven't actually tried it, but it might just work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM