CompletableFuture in Java 8

In this we will first discuss what is the benefit of completablefuture of Java 8 over Future

CompletableFuture was introduced to remove the limitation of Future Object in Java 8, lets first see what was the issue with Future Object

Consider the above code example where in order to fetch Manager Name from Department we need to hit 2 external service , in order to do that we have 2 methods,first we call

Future<String> futureDeptName = getEmployeeDepartment(e1.getDeptId());//this will give us future object containing department Name

Now after getting departmentName we hit another service which give us Manager Name from that department, but we need to call get method on future instance ( futureDeptName.get(); )before calling getManagerNameForDepartment, which ultimately blocks our call . So this is a issue as we are blocked until the result is available , to address this CompletableFuture was introduced.

CompletableFuture: A completable Future has a method thenApply to which we can pass post-processing function

CompletableFuture<String> compFutureDeptName = getEmployeeDepartment(e1.getDeptId());
CompletableFuture<String> result=compFutureDeptName.thenApply(CompletableFutureTest ::getManagerNameForDepartment);

1.thenApply  does not block, When first future gets completed its result is passed to thenApply method which result another future

2.supplyAsync Method: Source Code below

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
        return asyncSupplyStage(asyncPool, supplier);
    }

Supply Async method executes the code asynchronously and returns CompletableFuture when task completes , it takes Supplier as an arugment. Example I have given below

CompletableFuture compFuture = CompletableFuture.supplyAsync(()-> "Calculating and returning a in diff thread");
compFuture.thenApply((a) -> {return "Converting a to b";});

runAsync: Similar to supplyAsync which takes Supplier as an argument runAsync takes Runnable as an arugment and does not return any result,source code below

public static CompletableFuture runAsync(Runnable runnable) {
        return asyncRunStage(asyncPool, runnable);
    }

We can use supplyAsync and thenApply to chain the method calls in a non blocking way which we were not able to do using future.get()

Output

Here automatically when response from supplyAsync is returned it is sent to thenApply method and we did not call the future.get() method to get the response and pass it ,it was taken care on its own

Creating own Executor for CompletableFuture :

If require we can provide our own Executor in CompletableFuture and give the number of threads in Executor to use

You may also like...

Leave a Reply

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