Open In App

How to Use the ExecutorService.invokeAny Method in Java?

The ExecutorService interface in Java offers a strong management and control mechanism for asynchronous task execution. The InvokeAny() method is one of the helpful methods provided by this interface. This lets us submit numerous tasks and provides the outcome of the first one that is finished successfully.

In this article, we will learn how to use the ExecutorService.invokeAny method in Java.



Approaches to use the ExecutorService.invokeAny method

Program to Use the ExecutorService.invokeAny Method in Java

Below is the code implementation of the above-mentioned approaches.

Approach 1: Basic Usage without Timeout

Below is the Program to use the ExecutorService.invokeAny method without timeout:






// Java program to use the ExecutorService.invokeAny method without timeout
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
  
public class InvokeAnyExample {
    public static void main(String[] args) 
    {
        // Create an ExecutorService
        ExecutorService executor = Executors.newFixedThreadPool(3);
  
        // List of tasks
        List<Callable<String>> tasks = Arrays.asList(
            () -> "Result from Task 1",
            () -> "Result from Task 2",
            () -> "Result from Task 3"
        );
  
        try {
            // Invoke any and get the result of the first completed task
            String result = executor.invokeAny(tasks);
  
            // Print the result
            System.out.println("Result: " + result);
        } catch (InterruptedException | ExecutionException e) 
        {
            e.printStackTrace();
        } finally {
            // Shutdown the executor
            executor.shutdown();
        }
    }
}

Output
Result: Result from Task 3

Explanation of the above Program:

Approach 2: Usage with Timeout

Below is the Program to use the ExecutorService.invokeAny method with timeout:




// Java program to use the ExecutorService.invokeAny method with timeout
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
  
public class InvokeAnyWithTimeoutExample {
    public static void main(String[] args) {
        // create an ExecutorService
        ExecutorService executor = Executors.newFixedThreadPool(3);
  
        // list of tasks
        List<Callable<String>> tasks = Arrays.asList(
            () -> {
                TimeUnit.SECONDS.sleep(5);    // Simulate a long-running task
                return "Result from Task 1";
            },
            () -> "Result from Task 2",
            () -> "Result from Task 3"
        );
  
        try {
            // invoke any with a timeout of 3 seconds
            String result = executor.invokeAny(tasks, 3, TimeUnit.SECONDS);
  
            System.out.println("Result: " + result);
        } catch (InterruptedException | ExecutionException | TimeoutException e) 
        {
            e.printStackTrace();
        } finally {
            // shutdown the executor
            executor.shutdown();
        }
    }
}

Output
Result: Result from Task 2


Explanation of the above Program:


Article Tags :