CompletableFutures – why to use async methods?

I have been playing with Java 8 CompletableFutures and one thing has been bothering me – shall I use methods with Async suffix or the variant without it. Let’s take a look at the following example:

CompletableFuture.supplyAsync(() -> getUser(userId))
                .thenApply(CreditRatingService::getCreditRatingSystem1)
                .thenAccept(System.out::println);

private static User getUser(int id) {...}

private static CreditRating getCreditRatingSystem1(User user) {...}

Here I want to get some data about a user from a remote system, then call another system to get his credit rating and once it is finished, I want to print the result. All of the tasks may take some time, so I do not want to block the main thread, hence the use of completable futures.

If you are not yet familiar with Java 8 syntax, () -> getUser(userId) is a lambda calling getUser method. CreditRatingService::getCreditRatingSystem1 and System.out::println are method references. Underneath, the supplyAsync method creates a task which gets the user details. The task is submitted to fork-join thread pool and when it finishes, the result is passed to the next task. When the next task finishes, its result is sent further and so on. It’s quite neat and simple.

The question is, whether I should use the previous variant or this one.

CompletableFuture.supplyAsync(() -> getUser(userId))
                .thenApplyAsync(CreditRatingService::getCreditRatingSystem1)
                .thenAcceptAsync(System.out::println);

The difference is in the async suffix on the method names. The methods without async execute their task in the same thread as the previous task. So in the first example, all getUser, getCreditRating and println are executed in the same thread. It’s OK, it’s still a thread from the fork-join pool, so the main thread is not blocked.

The second variant always submits the succeeding task to the pool, so each of the tasks can be handled by different thread. The result will be the same, the first variant is a bit more effective due to less thread switching overhead. It does not make any sense to use the async variant here, so what is it good for? It was not clear to me, until extended the example to download the credit rating data from two different systems.

CompletableFuture<User> user = CompletableFuture.supplyAsync(() -> getUser(userId));

CompletableFuture<CreditRating> rating1 = 
    user.thenApplyAsync(CreditRatingService::getCreditRatingSystem1);
CompletableFuture<CreditRating> rating2 = 
    user.thenApplyAsync(CreditRatingService::getCreditRatingSystem2);

rating1
    .thenCombineAsync(rating2, CreditRating::combine)
    .thenAccept(System.out::println);

Here I have two actions waiting for user details. Once the details are available, I want to get two credit ratings from two different systems. Since I want to do it in parallel, I have to use at least one async method. Without async, the code would use only one thread so both credit rating tasks would be executed serially.

I have added combine phase that waits for both credit rating tasks to complete. It’s better to make this async too, but from different reason. Without async, the same thread as in rating1 would be used. But you do not want to block the thread while waiting for the rating2 task. You want to return it to the pool and get a thread only when it is needed.

When both tasks are ready, we can combine the result and print it in the same thread, so the last thenAccept is without async.

As we can see, both method variants are useful. Use async, when you need to execute more tasks in parallel or you do not want to block a thread while waiting for a task to finish. But since it is not easy to reason about such programs, I would recommend to use async everywhere. It might be little bit less effective, but the difference is negligible. For very small small price, it gives you the freedom to delegate your thinking to the machine. Just make everything async and let the fork-join framework care about the optimization.

One thought on “CompletableFutures – why to use async methods?

Comments are closed.