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
- Usage without Timeout
- Usage with Timeout
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
// 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:
- We have used the
ExecutorService.invokeAny
method to execute multiple tasks concurrently. - And it returns the result of the first task that completes.
- We have created a thread pool with three threads and submitted three tasks.
- The
invokeAny()
method blocks till one task is completed. - Then, it will return the result of the first completed task.
- The result of the first completed task is printed, and the thread pool is shutdown to release its resources.
Approach 2: Usage with Timeout
Below is the Program to use the ExecutorService.invokeAny method with timeout:
Java
// 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:
- We have created a thread pool with three threads and submits three tasks.
- Two of the tasks complete immediately, while the third task is designed to take five seconds to complete.
- The
invokeAny()
method is called with a timeout of three seconds. - Since the third task takes longer to complete than the timeout, a
TimeoutException
is thrown. - The program catches the exception and prints a message indicating that the timeout has occurred.
- At last, the thread pool is shut down to release its resources.
Contact Us