You could use an ExecutorService (containing multiple threads) to process your individual items of work by calling submit(). The submit method returns a Future, which will encapsulate either the result of the processing or any exception thrown. In other words, the threads within your ExecutorService
will not terminate if an exception occurs.
Example
First create an executor service containing more than one thread:
ExecutorService execService = Executors.newFixedThreadPool(5);
Define the item of work we wish to submit as a Callable
:
public class MyWorkItem implements Callable<Integer> {
public Integer call() throws Exception {
int result = new Random().nextInt(5);
// Randomly fail.
if (result == 0) {
throw new IllegalArgumentException("Fail!");
}
return result;
}
}
Submit some work for the executor service to do, and store the Future<Integer>
for each Callable<Integer>
.
List<Future<Integer>> futures = new LinkedList<Future<Integer>>();
for (int i=0; i<10; ++i) {
futures.add(execService.submit(new MyWorkItem()));
}
Now iterate over the futures attempting to retrieve the result of each work item (we could use a CompletionService
for this).
for (Future<Integer> future : futures) {
try {
Integer result = future.get();
} catch(Exception ex) {
// Handle exception.
}
}