CompletableFuture<T> class: join() vs get()
Solution 1:
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.