1. Introduction

In Java’s concurrent programming, CompletableFuture is a powerful tool that allows us to write non-blocking code. When working with CompletableFuture, we’ll encounter two common methods: join() and get(). Both methods are used to retrieve the result of a computation once it is complete, but they have some crucial differences.

In this tutorial, we’ll explore the differences between these two methods.

2. Overview of CompletableFuture

Before diving into join() and get(), let’s briefly revisit what CompletableFuture is. A CompletableFuture represents a future result of an asynchronous computation. It provides a way to write asynchronous code in a more readable and manageable way compared to traditional approaches like callbacks. Let’s see an example to illustrate the usage of CompletableFuture.

First, let’s create a CompletableFuture:

CompletableFuture<String> future = new CompletableFuture<>();

Next, let’s complete the future with a value:

future.complete("Hello, World!");

Finally, we retrieve the value using join() or get():

String result = future.join(); // or future.get();
System.out.println(result); // Output: Hello, World!

3. The join() Method

The join() method is a straightforward way to retrieve the result of a CompletableFuture. It waits for the computation to complete and then returns the result. If the computation encounters an exception, join() throws an unchecked exception, specifically a CompletionException.

Here’s the syntax for join():

public T join()

Let’s review the characteristics of the join() method:

  • Returns the result once the computation is complete
  • Throws an unchecked exception – CompletionException – if any computation involved in completing the CompletableFuture results in an exception
  • Since CompletionException is an unchecked exception, it does not require explicit handling or declaration in method signatures

4. The get() Method

On the other hand, the get() method retrieves the computation’s result and throws a checked exception if the computation encounters an error. The get() method has two variants: one that waits indefinitely and one that waits for a specified timeout.

Let’s review the syntax for the two variants of get():

public T get() throws InterruptedException, ExecutionException
public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException

And let’s look at the characteristics of the get() method:

  • Returns the result once the computation is complete
  • Throws a checked exception, which could be InterruptedException, ExecutionException, or TimeoutException
  • Requires explicit handling or declaration of checked exceptions in method signatures

The get() method is inherited from the Future interface, which CompletableFuture implements. The Future interface, introduced in Java 5, represents the result of an asynchronous computation. It defines the get() method to retrieve the result and handle exceptions that may occur during computation.

When CompletableFuture was introduced in Java 8, it was designed to be compatible with the existing Future interface to ensure backward compatibility with existing codebases. This necessitated the inclusion of the get() method in CompletableFuture.

5. Comparison: join() vs. get()

Let’s summarize the key differences between join() and get():

Aspect

join()

get()

Exception type

Throws CompletionException (unchecked)

Throws InterruptedException, ExecutionException, and TimeoutException (checked)

Exception handling

Unchecked, no need to declare or catch

Checked, must be declared or caught

Timeout support

No timeout support

Supports timeout

Origin

Specific to CompletableFuture

Inherited from Future interface

Usage Recommendation

Preferred for new code

For legacy compatibility

6. Tests

Let’s add some tests to ensure our understanding of join() and get() is correct:

@Test
public void givenJoinMethod_whenThrow_thenGetUncheckedException() {
    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Test join");

    assertEquals("Test join", future.join());

    CompletableFuture<String> exceptionFuture = CompletableFuture.failedFuture(new RuntimeException("Test join exception"));

    assertThrows(CompletionException.class, exceptionFuture::join);
}

@Test
public void givenGetMethod_whenThrow_thenGetCheckedException() {
    CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Test get");

    try {
        assertEquals("Test get", future.get());
    } catch (InterruptedException | ExecutionException e) {
        fail("Exception should not be thrown");
    }

    CompletableFuture<String> exceptionFuture = CompletableFuture.failedFuture(new RuntimeException("Test get exception"));

    assertThrows(ExecutionException.class, exceptionFuture::get);
}

7. Conclusion

In this quick article, we’ve learned that join() and get() are both methods used to retrieve the result of a CompletableFuture, but they handle exceptions differently. The join() method throws unchecked exceptions, making it easier to use when we don’t want to handle exceptions explicitly. On the other hand, the get() method throws checked exceptions, providing more detailed exception handling and timeout support. Generally, join() should be preferred for new code due to its simplicity, while get() remains available for legacy compatibility.

The example code from this article can be found over on GitHub.