Stop Executor when a Callable returns a specific result

1.8k Views Asked by At

I'd like to stop an Executor from running any more Future objects even if they have been submitted to the Executor. Getting multiple threads running though an Executor all works fine and well but the Executor should stop when one of the Callable's returns a Boolean TRUE. It's fine that the current running Future's complete but it would be a waste of time to continue the rest.

Set<Future<Boolean>> calculationSet = new HashSet<Future<Boolean>>();
threadPool = Executors.newFixedThreadPool(3);

int x = nextX();
int y = nextY();

do {
   Callable<Boolean> mathCalculation = new MathCalculation(x, y);
   Future<Boolean> futureAttempt = threadPool.submit(mathCalculation);
   calculationSet.add(futureAttempt);

   x = nextX();
   y = nextY();
} while (runSomeMore());

Where MathCalculation implements the Callable interface and its call() method returns a Boolean value.

Searching through the calculationSet on each iteration isn't an option since the set will become quite large and it will obviously not work because of the multi threaded situation. Is there a way to achieve this?

2

There are 2 best solutions below

1
On BEST ANSWER

You could also use ExecutorCompletionService

http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorCompletionService.html

There are two examples in top of this JavaDoc and second one says:

"Suppose ... that you would like to use the first non-null result of the set of tasks, ignoring any that encounter exceptions, and cancelling all other tasks when the first one is ready:", followed by sample code.

Thant sounds quite promising, does it solve your problem?

1
On

If you want the callable to stop the executor service, I suggest you create a wrapper or change the Callable to do it.

// performs a threadPool.shutdownNow() as required.
new MathCalculation(x, y, threadPool)