WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Concurrency · Expert · question 69 of 100

How does the Java ExecutorCompletionService class work and what is it used for?

📕 Buy this interview preparation book: 100 Java Concurrency questions & answers — PDF + EPUB for $5

The Java ExecutorCompletionService class is a utility class provided in the java.util.concurrent package that simplifies the use of Executor in concurrent programming. It is used to asynchronously execute multiple tasks concurrently and retrieve their results as they become available.

The ExecutorCompletionService class takes an Executor as input and provides a blocking take() method that retrieves the result of the next completed task. The results are returned in the order in which they completed, regardless of the order in which they were submitted.

Here is an example code that demonstrates the use of ExecutorCompletionService to submit multiple tasks and retrieve their results as they become available:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class Example {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);
        CompletionService<Integer> completionService = new ExecutorCompletionService<>(executor);

        List<Future<Integer>> futures = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            final int taskNum = i;
            futures.add(completionService.submit(() -> {
                System.out.println("Task " + taskNum + " started");
                Thread.sleep(1000);
                System.out.println("Task " + taskNum + " completed");
                return taskNum;
            }));
        }

        for (int i = 0; i < 10; i++) {
            try {
                Future<Integer> future = completionService.take();
                System.out.println("Result of task " + future.get() + " retrieved");
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        executor.shutdown();
    }
}

In this example, an ExecutorService is created with a fixed thread pool of 5 threads. A CompletionService is then created from this ExecutorService. The submit() method is used to submit 10 tasks to the completion service, each of which sleeps for 1 second before returning the task number.

The take() method is then used in a loop to retrieve the results of the tasks as they become available. Since the take() method blocks until a result is available, the results are printed in the order in which they complete.

Once all the tasks have completed, the ExecutorService is shut down.

In summary, the ExecutorCompletionService class simplifies the use of Executor in concurrent programming by allowing multiple tasks to be executed asynchronously and their results to be retrieved in the order in which they complete.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Concurrency interview — then scores it.
📞 Practice Java Concurrency — free 15 min
📕 Buy this interview preparation book: 100 Java Concurrency questions & answers — PDF + EPUB for $5

All 100 Java Concurrency questions · All topics