Skip to content
Advertisement

Stop ExecutorService on thread failure and exception handling

This is a simplified example I did to expose my problem. I have some task doSomeWork() that I handle in a multihreading fashion using ExecutorService (4 threads at a time max). However, if any of the threads/tasks generates an exception, I would like to:

  1. Stop any further tasks from being processed.

  2. Catch the exception at the main thread level.

    JavaScript

Currently, an execution would output something like this:

JavaScript

As you can see, indice 3 is missing, nevertheless the execution of the remaining threads completed. It also didn’t output anything about the exception.

My desired output would be something like this:

JavaScript

Other solutions I found around this problem were using a callable with a future but in a blocking fashion. I can’t block the execution of other threads while waiting for the future otherwise this whole multithreading is pointless.

Advertisement

Answer

You can do that using CompletableFuture. This is your main function I tested:

JavaScript

Utility function to make the joint future fail as soon as one of them is failed (or when all of them are completed):

JavaScript

And this is the output I get:

JavaScript

Explanation:

The method CompletableFuture.runAsync() allows you to provide with a Runnable (your doSomeWork) and an executor with a certain number of threads. Here, I pass an executor with 4 threads (as you did in your example).

Inside the runnable, I don’t only run the doSomeWork function but I also catch Exception and throw a RuntimeException (need to do that because Lambdas do not support checked exceptions, so I need to wrap it into a runtime one but it will still interrupt execution and be catched by your main).

Each time I create a new CompletableFuture<Void> for the task with the given index i, I will store this result into a list of completable futures.

The for loop will take nothing to execute, since the completable futures run asynchronously.

Hence, I create a joint completable future with CompletableFuture.allOf(...) and then I use the utility function failFast on this future in order to stop as soon as one of the task is failed (or to continue until all of them are complete).

So basically as soon as one of the futures fails throwing an exception, the joint future is considered to be completed and will hence leave the handle to your main thread which is, meanwhile, being hit by the RuntimeException that was thrown inside the lambda expression.

Note: thanks to Thomas’ comment, I’ve updated the code to use an ExecutorService instead of a simple Executor. That allows you to have a call to shutdownNow() inside your finally block after you catch the exception. As Thomas suggests, also, you may directly throw a RuntimeException inside your doSomeWork function so you don’t need to catch and wrap inside the lambda expression.

Other note: @matt made me notice something I didn’t know. The .allOf() future will be completed when ALL futures are completed, whether successfully or not. Hence, as he pointed out, my solution wouldn’t work as is. I’ve edited again the answer to take his comment into account, thanks @matt for making me notice.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement