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 80 of 100

How does the Java CompletableFuture class work and what are its benefits for multi-threading?

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

The Java CompletableFuture class was introduced in Java 8 as part of the java.util.concurrent package, providing a way to represent a task that will be completed in the future and can be chained with other tasks. CompletableFuture enables asynchronous and non-blocking execution of tasks, which can improve the performance of multi-threaded applications.

Here are some key features and benefits of the CompletableFuture class:

Provides a higher-level abstraction for chaining and combining multiple asynchronous tasks. Allows for composability and easy-to-understand code, as each asynchronous operation can be expressed as a CompletableFuture. Can be used with the Executor framework to provide different thread pools and control the number of threads. Provides methods for error handling and dealing with exceptions. Supports various types of completion events, including normal completion, exception, and cancellation.

Let’s take a look at some examples of how to use the CompletableFuture class.

First, let’s create a simple example of a CompletableFuture that completes with a result after a specified delay:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new IllegalStateException(e);
            }
            return "Result of the asynchronous computation";
        });

        System.out.println("Do something else while waiting for the future...");
        // Block and wait for the future to complete
        String result = future.join();
        System.out.println("Result: " + result);
    }
}

In this example, we create a CompletableFuture using the supplyAsync method, which runs the specified function asynchronously and returns a CompletableFuture that will be completed with the result of the function. We then do some other work while waiting for the future to complete, and finally call the join method to block and wait for the future to complete and return its result.

Next, let’s look at an example of chaining multiple CompletableFutures:

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public class CompletableFutureExample {
    public static void main(String[] args) {
        CompletableFuture.supplyAsync(() -> "Hello")
        .thenApplyAsync(s -> s + " World")
        .thenAcceptAsync(System.out::println);
    }
}

In this example, we use the thenApplyAsync method to chain two CompletableFutures together. The first CompletableFuture returns the string "Hello", and the second CompletableFuture applies the thenApplyAsync function to the result of the first future, appending " World" to the string. Finally, we use thenAcceptAsync to print the result of the second future.

These are just a few examples of how to use the CompletableFuture class in Java. The CompletableFuture class provides a flexible and powerful way to manage asynchronous tasks and improve the performance of multi-threaded applications.

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