Class ExecutorServiceResultsHandler<V>

  • All Implemented Interfaces:
    Iterable<V>

    public class ExecutorServiceResultsHandler<V>
    extends Object
    implements Iterable<V>
    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:

    1. Create an ExecutorService and pass it to the constructor.
    2. Create Callables and ensure that they respond to interruption, e.g. regularly call:
      
           if (Thread.currentThread().isInterrupted()) {
               throw new RuntimeException("The thread was interrupted, likely indicating failure in a sibling thread.");
           }
    3. Pass the callables to the submit() method.
    4. Call finishedSubmitting().
    5. 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

    You can also call abort() to shut down the threads yourself.

    • Constructor Detail

      • ExecutorServiceResultsHandler

        public ExecutorServiceResultsHandler​(ExecutorService executorService)
    • Method Detail

      • submit

        public void submit​(Callable<V> task)
      • finishedSubmitting

        public void finishedSubmitting()
      • abort

        public void abort()
      • awaitCompletion

        public void awaitCompletion()
        Convenience method to wait for the callables to finish for when you don't care about the results.