Java 8 CompletableFutures

Java 8 multithreading programming has an important feature named CompletableFuture.
In previous post about Java Future, we have the concept of a Future object, which can help us make something done while waiting for other things. However, although we can inspect Future objects to see if they’re done, what if we wanna execute some code whenever its ready? We still have to wait until the result is available.

CompletableFuture meets the requirement, and more than that.

Related articles:
Java Future
CompletableFuture Handle Exception
Java 8 Multiple CompletableFutures

I. Create CompletableFuture

We use one of those factory methods to create a CompletableFuture object:

If we don’t provide any Executor object as input parameter, the method will use ForkJoinPool.commonPool()

In this example, we use that global, general purpose pool ForkJoinPool.commonPool():

II. Transform results

If we wanna do more things after the result is available, CompletableFuture has thenApply() method:

We will make some operations in chain: parse String to Integer, do math operation, and create a String result in the example:

Just like supplyAsync() method above, we can apply those operations asynchronously in different thread pool by using:

III. Complete a future
1. Final stage

thenApply() return a CompletableFuture object with specific Type, but thenAccept() returns a CompletableFuture<Void>.

We doesn’t need a thenAccept() as final stage to make the future object work at the end. It just helps us do more things. But we need complete method or get method to make a final actually.

2. complete method

The complete method sends the result to the future despite transformation that the operations have done before.

The code above will show the result:

3. get method

Just like Java Future, we use get() to retrieve the result of the completion when it completes:

IV. Source code

Check results in Console Screen:


Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*