Category : Java | Sub Category : ExecutorService | By Prasad Bonam Last updated: 2020-11-30 06:44:12 Viewed : 521
Executes
the given tasks, returning the result of one that has completed successfully
(i.e., without throwing an exception), if any do. Upon normal or exceptional
return, tasks that have not completed are cancelled. The results of this method
are undefined if the given collection is modified while this operation is in
progress.
ExecutorServiceAnyEx.java
package runnerdev;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import
java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import
java.util.concurrent.ExecutorService;
public class ExecutorServiceAnyEx {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
Set<Callable<String>> callables = new HashSet<Callable<String>>();
callables.add(new Callable<String>() {
public String call() throws Exception {
return "Task
11";
}
});
callables.add(new Callable<String>() {
public String call() throws Exception {
return "Task
22";
}
});
callables.add(new Callable<String>() {
public String call() throws Exception {
return "Task
13";
}
});
String result = executorService.invokeAny(callables);
System.out.println("result => " + result);
executorService.shutdown();
}
}
Output:
result
=> Task 11