CompletableFuture in Java
Last Updated :
14 May, 2023
CompletableFuture provides a powerful and flexible way to write asynchronous, non-blocking code. It was introduced in Java 8 and has become popular due to its ease of use and ability to handle complex asynchronous workflows
What is CompletableFuture?
CompletableFuture is a class in java.util.concurrent package that implements the Future and CompletionStage Interface. It represents a future result of an asynchronous computation. It can be thought of as a container that holds the result of an asynchronous operation that is being executed in a different thread. It provides a number of methods to perform various operations on the result of the async computation.
Creating a CompletableFuture
To create an instance of CompletableFuture, we can use the static method supplyAsync provided by CompletableFuture class which takes Supplier as an argument. Supplier is a Functional Interface that takes no value and returns a result.
Java
import java.util.concurrent.*;
class GFG {
public static void main(String[] args) throws Exception
{
CompletableFuture<String> greetingFuture
= CompletableFuture.supplyAsync(() -> {
// some async computation
return "Hello from CompletableFuture";
});
System.out.println(greetingFuture.get());
}
}
Output:
Hello from CompletableFuture
This creates a CompletableFuture that will execute the lambda function passed to supplyAsync in a separate thread. And after the execution, the result lambda function is returned by CompletableFuture Object
Composing CompletableFuture
One of the powerful features of CompletableFuture is its ability to compose multiple asynchronous operations. We can use methods like thenApply, thenCombine, thenCompose to perform operations on the result of one CompletableFuture and create a new CompletableFuture as a result.
Java
/*package whatever //do not write package name here */
import java.util.concurrent.*;
class GFG {
public static void main(String[] args) throws Exception
{
CompletableFuture<String> helloFuture
= CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> greetingFuture
= CompletableFuture.supplyAsync(() -> "World");
CompletableFuture<String> combinedFuture
= helloFuture.thenCombine(
greetingFuture, (m1, m2) -> m1 + " " + m2);
System.out.println(combinedFuture.get());
}
}
Output:
Hello World
This creates two instances of CompletableFuture that return "hello" and "world". And using thenCombine, the result of both the CompletableFutures are concatenated and returned as a final result.
Handling Exception in CompletableFuture
CompletableFuture provides methods like exceptionally and handle to handle exceptions and errors that might happen during asynchronous computation and provide a fallback value or perform some alternative operation.
Java
import java.util.concurrent.*;
class GFG {
public static void main(String[] args) throws Exception
{
CompletableFuture<Integer> resultFuture
// java.lang.ArithmeticException: / by zero
= CompletableFuture.supplyAsync(() -> 10 / 0)
.exceptionally(ex -> 0);
// 0 - returned by exceptionally block
System.out.println(resultFuture.get());
}
}
Output:
0
Inside supplyAsync, when 10 is divided by 0, It will throw ArithmeticException and control will go to exceptionally block and which in turn returns 0.
Conclusion
In summary, CompletableFuture provides a powerful and flexible way to write asynchronous, non-blocking code in Java. We can use it to compose multiple asynchronous operations, handle errors and exceptions, and combine multiple CompletableFutures into one. By using CompletableFuture, we can write more efficient and scalable code that can take advantage of multi-core processors and handle complex asynchronous workflows.
Similar Reads
Callable and Future in Java
Prerequisite: Threads, Multi-threading The need for Callable There are two ways of creating threads â one by extending the Thread class and other by creating a thread with a Runnable. However, one feature lacking in  Runnable is that we cannot make a thread return result when it terminates, i.e. whe
6 min read
ConcurrentLinkedQueue in Java
In Java, the ConcurrentLinkedQueue is the part of the java.util.concurrent package and implements a FIFO(First-In-First-Out) queue. It is a thread-safe, non-blocking, and scalable queue designed for use in highly concurrent environments. The queue uses a lock-free algorithm, ensuring that multiple t
8 min read
Java 8 Features - Complete Tutorial
Java 8 is the most awaited release of the Java programming language development because, in the entire history of Java, it has never released that many major features. It consists of major features of Java. It is a new version of Java and was released by Oracle on 18 March 2014. Java provided suppor
9 min read
Hashtable in Java
Hashtable class, introduced as part of the Java Collections framework, implements a hash table that maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method an
12 min read
Java Collectors
Collectors is one of the utility class in JDK which contains a lot of utility functions. It is mostly used with Stream API as a final step. In this article, we will study different methods in the collector class. When it comes to the functional style of programming in Java, we typically have few fun
13 min read
ConcurrentLinkedDeque in Java
The ConcurrentLinkedDeque class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractCollection class. It belongs to java.util.concurrent package. It is used to implement Deque with the help of LinkedList concurrently.Iterators and spliterators a
10 min read
Future and FutureTask in java
Prerequisite: Future and callable Future: A Future interface provides methods to check if the computation is complete, to wait for its completion and to retrieve the results of the computation. The result is retrieved using Future's get() method when the computation has completed, and it blocks unti
3 min read
Hashtable clear() Method in Java
The java.util.Hashtable.clear() method in Java is used to clear and remove all of the keys from a specified Hashtable. Syntax: Hash_table.clear() Parameters: The method does not accept any parameters. Return Value: The method does not return any value. Below programs are used to illustrate the worki
2 min read
Java Features
Java is a high-level, object-oriented programming language. It is known for its platform independence, reliability, and security. Java Programming language follows the "Write Once, Run Anywhere" principle. It provides various features like portability, robustness, simplicity, multithreading, and hig
6 min read
BlockingDeque in Java
In Java, the BlockingDeque interface is a part of the Java Collections Framework. It is an interface that extends Deque (double-ended queue) and provides methods for thread-safe operation. It allows threads to safely add and remove elements from both ends of the queue.BlockingDeque supports thread-s
12 min read