Introduction about CompletableFuture in Java

In the previous tutorial, I introduced to you all about the Future object in Java and I also told you that when using the get() method of the Future object, our program will be blocked until when all the tasks completed. To solve this blocking problem, from version 8, Java introduces the CompletableFuture object to help us solve this problem. How is it in details? Let’s find out in this tutorial.

To make it easier to compare the Future object and the CompletableFuture object, we will use the Future object as an example first.

My Callable object will have the following contents:

Notice that in the call() method of the Callable object, I am sleeping the code 3s to demo for long thread processing.

Now I will write a main class using the Future object. The code for this class is as follows:

When running this example, you will see after 3 seconds we will get the result and then print the output and the “End ..” line is also output:

Introduction about CompletableFuture in Java

Now, I’m going to use the CompletableFuture object so that our program is not blocked and will get the same result as when using the Future object.

First, we need to submit the Calculator object to another thread first. CompletableFuture has many different methods that help us do this. In this tutorial, I will use the supplyAsync() method, which will help us get the results after completing the task.

The parameter of the supplyAsync() method is a Supplier interface so we need to modify the Calculator class implementing a Supplier interface.

And now in the main class, we do not need to use the Executor Framework anymore because CompletableFuture will do our job in another thread. The main class we can now rewrite is as follows:

To be able to retrieve the result after the execution of the task in the get() method of the Calculator object completed and print the output to the console, I will use the CompleTextFuture’s thenAccept() method with the parameter is a Consumer interface which will hold value after the task is finished.

The code of the main class will now look like this:

When running the above code, you will see the line “End …” will be printed first. After 3 seconds, after processing the task, the result is returned and assigned to the result variable. At this point, the results will also be printed.

Introduction about CompletableFuture in Java

Obviously, our program is no longer blocked.

 

Add Comment