如何在ExecutorService中的任何Thread / Runnable / Callable在等待终止时失败时捕获异常

时间:2015-09-30 12:04:54

标签: java multithreading exception-handling future executorservice

我目前的代码看起来像这样:

public void doThings() {
    int numThreads = 4;
    ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
    for (int i = 0; i < numThreads; i++) {

        final int index = i;
        Runnable runnable = () -> {

            // do things based on index
        };

        threadPool.execute(runnable);

    }

    threadPool.shutdown();

    try {
        // I'd like to catch exceptions here from any of the runnables
        threadPool.awaitTermination(1, TimeUnit.HOURS);
    } catch (InterruptedException e) {
        Utils.throwRuntimeInterruptedException(e);
    }
}

基本上我会创建大量并行工作并等待所有工作完成。如果任何处理失败,我需要快速了解并中止所有处理。 threadPool.awaitTermination似乎没有注意到是否在其中一个线程中抛出异常。我只是在控制台中看到一个堆栈跟踪。

我对并发性了解不多,所以我在所有可用的接口/对象中丢失了一些内容,例如CallableFutureTask

我看到threadPool.invokeAll(callables)会给我一个List<Future>Future.get()可以在线程中抛出异常,但是如果我打开它(如果callable在它自己引发异常)线)。但是,如果我.get我在序列集合中拥有每个可调用者,那么在所有其他人完成之前,我不会知道最后一个失败。

我最好的猜测是有一个队列,runnables为成功或失败放置Boolean,然后从队列中take()多次出现线程。

我觉得这是一个非常复杂的复杂程度(即使只是我粘贴的代码有点令人惊讶的长),这似乎是一个非常常见的简单用例。而且,当一个失败时,这甚至不包括中止runnables。必须有一个更好的方法,作为一个初学者,我不知道。

1 个答案:

答案 0 :(得分:0)

我最终发现ExecutorCompletionService就是为此设计的。然后我写了下面的类来抽象过程并简化一些用法:

import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Wrapper around an ExecutorService that allows you to easily submit Callables, get results via iteration,
 * and handle failure quickly. When a submitted callable throws an exception in its thread this
 * will result in a RuntimeException when iterating over results. Typical usage is as follows:
 *
 * <ol>
 *     <li>Create an ExecutorService and pass it to the constructor.</li>
 *     <li>Create Callables and ensure that they respond to interruption, e.g. regularly call: <pre>{@code
 *     if (Thread.currentThread().isInterrupted()) {
           throw new RuntimeException("The thread was interrupted, likely indicating failure in a sibling thread.");
 *     }}</pre></li>
 *     <li>Pass the callables to the submit() method.</li>
 *     <li>Call finishedSubmitting().</li>
 *     <li>Iterate over this object (e.g. with a foreach loop) to get results from the callables.
 *     Each iteration will block waiting for the next result.
 *     If one of the callables throws an unhandled exception or the thread is interrupted during iteration
 *     then ExecutorService.shutdownNow() will be called resulting in all still running callables being interrupted,
 *     and a RuntimeException will be thrown </li>
 * </ol>
 */
public class ExecutorServiceResultsHandler<V> implements Iterable<V> {

    private ExecutorCompletionService<V> completionService;
    private ExecutorService executorService;
    AtomicInteger taskCount = new AtomicInteger(0);

    public ExecutorServiceResultsHandler(ExecutorService executorService) {
        this.executorService = executorService;
        completionService = new ExecutorCompletionService<V>(executorService);
    }

    public void submit(Callable<V> task) {
        completionService.submit(task);
        taskCount.incrementAndGet();
    }

    public void finishedSubmitting() {
        executorService.shutdown();
    }

    @Override
    public Iterator<V> iterator() {
        return new Iterator<V>() {
            @Override
            public boolean hasNext() {
                return taskCount.getAndDecrement() > 0;
            }

            @Override
            public V next() {
                Exception exception;
                try {
                    return completionService.take().get();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    exception = e;
                } catch (ExecutionException e) {
                    exception = e;
                }
                executorService.shutdownNow();
                executorService = null;
                completionService = null;
                throw new RuntimeException(exception);
            }
        };
    }

    /**
     * Convenience method to wait for the callables to finish for when you don't care about the results.
     */
    public void awaitCompletion() {
        for (V ignored : this) {
            // do nothing
        }
    }

}