java - Stop Executor when a Callable returns a specific result -


i'd stop executor running more future objects if have been submitted executor. getting multiple threads running though executor works fine , executor should stop when 1 of callable's returns boolean true. it's fine current running future's complete waste of time continue rest.

set<future<boolean>> calculationset = new hashset<future<boolean>>(); threadpool = executors.newfixedthreadpool(3);  int x = nextx(); int y = nexty();  {    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 callable interface , call() method returns boolean value.

searching through calculationset on each iteration isn't option since set become quite large , not work because of multi threaded situation. there way achieve this?

you use executorcompletionservice

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

there 2 examples in top of javadoc , second 1 says:

"suppose ... use first non-null result of set of tasks, ignoring encounter exceptions, , cancelling other tasks when first 1 ready:", followed sample code.

thant sounds quite promising, solve problem?


Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -