ExecutorService using invokeAny () method

Category : Java | Sub Category : ExecutorService | By Prasad Bonam Last updated: 2020-11-30 06:44:12 Viewed : 510


 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:
RECxoRZFB
at 2023-11-16 12:53:14
However, a potential benefit was noted among women with stage I tumors, warranting further investigation <a href=http://cials.buzz>buy cialis online in usa</a> Furthermore, PKC О± overexpression may be predictive of TAM treatment failure, since expression is high in the primary biopsy and does not increase in the second biopsy following TAM exposure