Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
CompletableFuture | Multithreading Best Practices
Multithreading in Java
course content

Conteúdo do Curso

Multithreading in Java

Multithreading in Java

1. Multithreading Basics
2. Synchronized Collections
3. High-level Synchronization Mechanisms
4. Multithreading Best Practices

CompletableFuture

There's one last leap left! In this chapter we will look at the main asynchrony class CompletableFuture.

Let’s use a real-life analogy. You hail a cab using an app (task creation). While you wait, the app can provide updates on the car’s location or the estimated arrival time (result processing). If there are issues such as delays or cancellations, the app will notify you and suggest alternatives (exception handling).

Main Methods

The first question you might ask is how to start a task using CompletableFuture. To do this, you can use the supplyAsync() method, which is designed to execute a task that returns the result asynchronously.

java

Main

We also have the thenAccept() method, which handles the value returned from CompletableFuture in asynchronous code. It does not return anything; it is useful when you need to accept a response and process it in some way.

Note

In our example, we run the task asynchronously, and future.thenAccept() gets the response from the lambda, which we can then use to print to the console.

There's a similar method, thenApply(), which works like thenAccept() but gets the result of the asynchronous task and returns a new result.

java

Main

What if we don't want to get the result of the asynchronous task but simply want to be notified when it has finished?

For this, we can use thenRun(), which is executed after the asynchronous task completes.

java

Main

We can also retrieve the result of an asynchronous task by blocking the current thread until the task is completed. For this purpose, we use the get() method.

java

Main

There is also a method join(), which also pauses the current thread and waits for the asynchronous task to complete. However, the difference between join() and get() is that they throw different exceptions.

java

Main

We are not handling the exception here because the join() method throws an unchecked CompletionException.

Combining Tasks and Chaining them Together

We can combine tasks in CompletableFuture using thenCompose() which will combine 2 dependent tasks.

java

Main

We first retrieve the book data asynchronously using the getBookDetails() method, and then use the result to carry out the next asynchronous task—fetching the author data through the getAuthorDetails() method. After both tasks are complete, the result (author information) is displayed on the console.

We can also merge the results of two tasks using the thenCombine() method. It executes both tasks concurrently and combines their results once both tasks are complete.

java

Main

This code asynchronously retrieves two numbers, sums them, and prints the result to the console.

We can also wait for all tasks to complete using the allOf() method, or any one of them using the anyOf() method.

java

Main

How do you Handle Errors and What is a Timeout?

Short Clip From the Video

  • handle(): Processes the result or handles any exceptions thrown by the CompletableFuture;
  • exceptionally(): Handles exceptions thrown during the execution of the CompletableFuture;
  • completeOnTimeout(): Completes the CompletableFuture with a specified value if it times out before completing.

Summary

CompletableFuture makes it easy to manage asynchronous tasks and process their results, making it a powerful tool for developing modern applications.

Tudo estava claro?

Seção 4. Capítulo 6
We're sorry to hear that something went wrong. What happened?
some-alt