3

I need to properly shut down two instances of Executor Service in one method.

Here's my simplified code:

ExecutorService executor1 = Executors.newSingleThreadExecutor();
ScheduledExecutorService executor2 = Executors.newSingleThreadScheduledExecutor();
// logic here
executor1.shutdown();
executor2.shutdown();
try {
    if (!executor1.awaitTermination(1, TimeUnit.SECONDS)) {
        executor1.shutdownNow();
    }
} catch (InterruptedException ex) {
    throw new IllegalStateException(ex);
}
try {
    if (!executor2.awaitTermination(1, TimeUnit.SECONDS)) {
        executor2.shutdownNow();
    }
} catch (InterruptedException ex) {
    throw new IllegalStateException(ex);
}

InterruptedException is converted to IllegalStateException as I don't expect any interruptions here and this would mean my application went into illegal state.

I see one flaw in this solution - whenever first executor while shutting down throws exception, the second executor won't be properly closed. What should be correct approach here? How to safely close two instances of ExecutorService?

I'd rather like to avoid nested try-finally blocks, as I might need to add third executor service and code would become unmanageable.

6
  • Is this the same as: stackoverflow.com/questions/25330464/… ? Commented Dec 28, 2015 at 19:23
  • @YacoZaragoza not really - here my code sample is simplified, but I need two separate executor services, as one is normal, but second is scheduled executor service. Commented Dec 28, 2015 at 19:25
  • Got it.. Let me run some test :-) Commented Dec 28, 2015 at 19:26
  • When both shutdowns raise an exception, which one do you want to keep? If you want to keep both, you will need a wrapper exception to contain them.
    – dhke
    Commented Dec 28, 2015 at 19:31
  • Safe info if first faulted then handle second then throw exception after last executor has been handled according to prior safed info.
    – Fildor
    Commented Dec 28, 2015 at 19:32

1 Answer 1

2

As for a similar situation:

Apache Commons IO has a closeQuietly() that closes streams (or rather any Closeable) while ignoring any exception during close.

public void shutdownQuietly(ExecutorService executor)
{
    try {
        if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
            executor.shutdownNow();
        }
    } catch (InterruptedException ex) {
       /* IGNORE */
    }  
}

If you need those exception, you can try some slightly more evil trickery:

class MultiExecutorShutdown
{
     private final List<InterrupedException> exceptions = new ArrayList<>();

     public void shutdown(ExecutorService service)
     {
         try {
             if (!executor.awaitTermination(1, TimeUnit.SECONDS)) {
                executor.shutdownNow();
             }
         } catch (InterruptedException ex) {
             exceptions.add(ex);
         }
     }

     public Optional<InterruptedException> getLastException()
     {
         if (exceptions.isEmpty()) {
            return Optional.empty();
         } else {
             return exceptions.get(exceptions.size() - 1);
         }
     }

     public Optional<InterruptedException> getFirstException()
     {
         if (exceptions.isEmpty()) {
            return Optional.empty();
         } else {
             return exceptions.get(0);
         }
     }
}


[...]
MultiExecutorShutdown multiShutdown = new MultiExecutorShutdown();
multiShutdown.shutdown(executor1);
multiShutdown.shutdown(executor2);
multiShutdown.shutdown(executor3);

Optional<InterruptedException> exception = multiShutdown.getLastException();
// alternative:
// Optional<InterruptedException> exception = multiShutdown.getFirstException();

if (exception.isPresent()) {
   throw new IllegalStateException(exception.get());
}

If you also need the executor which failed, you can also modify MultiExecutorShutdown to keep an (ordered) map ExecutorService -> Exception.

You can also push the throw into MultiExecutorShutdown itself, making it even more usable. And finally the whole thing can --of course-- be abstracted so that it takes a functional, calls that and records any exceptions thrown.

2
  • If each of your three ExecutorServices throws an exception you will be unable to access them with first and last accessor methods only.
    – harpun
    Commented Dec 28, 2015 at 20:03
  • @harpun Correct. The implementation needs to be tailored to the specific use case. If you need all three exceptions, add the appropriate accessor method. You might even use a strategy pattern to make the resolution pluggable, but that may be overengineering the solution.
    – dhke
    Commented Dec 29, 2015 at 21:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.