ExecutorService using invokeAny () method

Category : Java | Sub Category : ExecutorService | By Runner Dev Last updated: 2020-11-30 12:14:12 Viewed : 198


 1. ExecutorService using invokeAny () method

<String> String java.util.concurrent.ExecutorService.invokeAny(Collection<? extends Callable<String>> tasks) throws InterruptedException, ExecutionException

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.

 

2.  Example:

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

Search
Related Articles

Leave a Comment:
Deegums
at 2022-04-16 21:00:42
Rapidtabs Qriddt https://bestadalafil.com/ - Cialis <a href="https://bestadalafil.com/">cialis without prescription</a> Contrast Studies. Gphvmh https://bestadalafil.com/ - Cialis Buy Synthroid Cheap