ExecutorService using invokeAll () method

Category : Java | Sub Category : ExecutorService | By Prasad Bonam Last updated: 2020-11-30 06:48:25 Viewed : 801


 1. ExecutorService using invokeAll () method

·       <String> List<Future<String>> java.util.concurrent.ExecutorService.invokeAll(Collection<? extends Callable<String>> tasks) throws InterruptedException

Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone is true for each element of the returned list. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.

 

·       String java.util.concurrent.Future.get() throws InterruptedException, ExecutionException

Waits if necessary for the computation to complete, and then retrieves its result.

2.  Example:

ExecutorServiceAllEx.java

 

package runnerdev;

 

import java.util.HashSet;

import java.util.List;

import java.util.Set;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

import java.util.concurrent.ExecutorService;

 

public class ExecutorServiceAllEx {

 

     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";

              }

         });

 

         List<Future<String>> results = executorService.invokeAll(callables);


         for (Future<String> future : results) {

              System.out.println("future.get => " + future.get());

         }

 

         executorService.shutdown();

     }

} 

Output:

future.get => Task 11

future.get => Task 13

future.get => Task 22

Search
Related Articles

Leave a Comment: