182

What is the difference between the get() and join() methods of the CompletableFuture<T> class?

Below is the my code:

List<String> process() {

    List<String> messages = Arrays.asList("Msg1", "Msg2", "Msg3", "Msg4", "Msg5", "Msg6", "Msg7", "Msg8", "Msg9",
            "Msg10", "Msg11", "Msg12");
    MessageService messageService = new MessageService();
    ExecutorService executor = Executors.newFixedThreadPool(4);

    List<String> mapResult = new ArrayList<>();

    CompletableFuture<?>[] fanoutRequestList = new CompletableFuture[messages.size()];
    int count = 0;
    for (String msg : messages) {
        CompletableFuture<?> future = CompletableFuture
                .supplyAsync(() -> messageService.sendNotification(msg), executor).exceptionally(ex -> "Error")
                .thenAccept(mapResult::add);

        fanoutRequestList[count++] = future;
    }

    try {
        CompletableFuture.allOf(fanoutRequestList).get();
      //CompletableFuture.allOf(fanoutRequestList).join();
    } catch (InterruptedException | ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return mapResult.stream().filter(s -> !s.equalsIgnoreCase("Error")).collect(Collectors.toList());
}

I have tried with both methods but I see no difference in result.

Nomeswaran
  • 1,831
  • 2
  • 10
  • 7
  • 17
    `get()` requires you to catch checked exceptions. You should notice the difference when you change from `get()` to `join()`, as you will imediately get a compiler error saying that neither `InterruptedException` nor `ExecutionException` are thrown in the `try` block. – Holger Aug 03 '17 at 16:58
  • 9
    @holi-java: `join()` can not get interrupted. – Holger Aug 03 '17 at 17:48
  • @Holger yes, sir. I found I can't interrupt the task. – holi-java Aug 03 '17 at 19:14
  • @Holger, Thank you for reply and you are correct, get expects checked exception and join method not. But both are waiting for complete the all the future and I would like know whcih one I should use and why? – Nomeswaran Aug 04 '17 at 03:26
  • 14
    Well `get` exists, because `CompletableFuture` implements the `Future` interface which mandates it. `join()` most likely has been introduced, to avoid needing to catch checked exceptions in lambda expressions when combining futures. In all other use cases, feel free to use whatever you prefer. – Holger Aug 06 '17 at 14:26
  • 3
    Does it really make sense to use join or get as both block on the thread. Can't we instead make this asynchronous by using other composition methods to create a chain of asynchronous functions.ofvourse it depends on functionality. But in case of e.g. a service method in spring called by controller method returning completeable future it makes more sense to not call get or join in service method at all .does it? – Shailesh Vaishampayan Aug 31 '17 at 23:21

2 Answers2

187

The only difference is how methods throw exceptions. get() is declared in Future interface as:

V get() throws InterruptedException, ExecutionException;

The exceptions are both checked exceptions which means they need to be handled in your code. As you can see in your code, an automatic code generator in your IDE asked to create try-catch block on your behalf.

try {
  CompletableFuture.allOf(fanoutRequestList).get() 
} catch (InterruptedException | ExecutionException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

The join() method doesn't throw checked exceptions.

public T join()

Instead it throws unchecked CompletionException. So you do not need a try-catch block and instead you can fully harness exceptionally() method when using the disscused List<String> process function

CompletableFuture<List<String>> cf = CompletableFuture
    .supplyAsync(this::process)
    .exceptionally(this::getFallbackListOfStrings) // Here you can catch e.g. {@code join}'s CompletionException
    .thenAccept(this::processFurther);

You can find both get() and join() implementation here.

Dawid Wróblewski
  • 1,871
  • 1
  • 7
  • 4
14

In addition to the answer provided by Dawid, the get method is available in two flavors:

get()
get(Long timeout, TimeUnit timeUnit) 

The second get takes wait time as an argument and waits for at most the provided wait time.

try {
    System.out.println(cf.get(1000, TimeUnit.MILLISECONDS));
} catch (InterruptedException | ExecutionException | TimeoutException ex) {
    ex.printStackTrace();
}

You can refer to this documentation for more information.

  1. join() is defined in CompletableFuture whereas get() comes from interface Future
  2. join() throws unchecked exception whereas get() throws checked exceptions
  3. You can interrupt get() and then throws an InterruptedException
  4. get() method allows to specify the maximum wait time
Praj
  • 451
  • 2
  • 5
  • 3
    This is a good answer. While it's mostly recommended to use join one limitation of join is that you can't set timeout. get helps overcome this limitation. – bluelurker Sep 07 '22 at 21:04