WalzoneInterview Prep
πŸ“ž Interviewing soon? Practice with a realistic AI mock phone interview β€” it calls you, then scores you. First 15 min FREE β†’

Java Concurrency Β· Guru Β· question 98 of 100

How can you use the Java CompletableFuture class to implement asynchronous and parallel computations?

πŸ“• Buy this interview preparation book: 100 Java Concurrency questions & answers β€” PDF + EPUB for $5

Java 8 introduced the CompletableFuture class, which provides a powerful mechanism for asynchronous programming. It is a higher-level abstraction of the traditional Future class, allowing developers to more easily compose and combine asynchronous operations.

Here are some ways to use the CompletableFuture class in Java:

Creating a CompletableFuture

You can create a CompletableFuture instance in several ways. The simplest way is to use the CompletableFuture constructor:

CompletableFuture<String> future = new CompletableFuture<>();

You can also use the CompletableFuture.supplyAsync() method to create a CompletableFuture instance that returns a result asynchronously:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello, World!");

Composing CompletableFutures

One of the key benefits of CompletableFuture is that it allows you to easily compose and combine multiple asynchronous operations. For example, you can use the thenApply() method to apply a function to the result of a CompletableFuture:

CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello, World!")
.thenApply(s -> s + "!")
.thenApply(String::toUpperCase);

System.out.println(future.get());

In this example, the thenApply() method is used to chain together three operations:

The supplyAsync() method returns a CompletableFuture that asynchronously supplies the string "Hello, World!". The first thenApply() method appends a "!" to the string. The second thenApply() method converts the resulting string to uppercase.

The get() method blocks until the operation is complete and returns the final result.

Combining CompletableFutures

You can also use the thenCompose() method to combine CompletableFuture instances into a single instance:

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> "World");

CompletableFuture<String> combinedFuture = future1.thenCompose(s1 ->
    future2.thenApply(s2 -> s1 + " " + s2)
);

System.out.println(combinedFuture.get());

In this example, two CompletableFuture instances are created, each of which returns a string asynchronously. The thenCompose() method is used to combine the two futures into a single future that returns the concatenated string "Hello World".

Exception Handling

Like traditional Future instances, CompletableFuture instances can also handle exceptions that occur during computation. You can use the exceptionally() method to handle exceptions that occur in a CompletableFuture:

CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 7 / 0)
.exceptionally(ex -> 0);

System.out.println(future.get());

In this example, the supplyAsync() method returns a CompletableFuture that will throw an exception (in this case, a java.lang.ArithmeticException). However, the exceptionally() method is used to handle the exception and return a default value of zero.

Overall, the CompletableFuture class is a powerful tool for implementing asynchronous and parallel computations in Java. It provides an easy-to-use API for composing and combining operations, and offers robust exception handling capabilities.

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