What is CompletableFuture.join() in Java?
Overview
join() is an instance method of the CompletableFuture class. It is used to return the value when the future is complete or throws an unchecked exception if completed exceptionally. If the task involved in the completion of the CompletableFuture raises an exception, then this method throws a CompletionException with the underlying exception as its cause.
The join method is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package. To import the CompletableFuture class, check the following import statement.
import java.util.concurrent.CompletableFuture;
Syntax
public T join()
Parameters
This method has no parameters.
Return value
This method returns the result value stored in the future.
Example
import java.util.concurrent.*;public class Main {static void sleep(int millis){try {Thread.sleep(millis);} catch (InterruptedException e) {e.printStackTrace();}}public static void main(String[] args){CompletableFuture<String> completableFuture = CompletableFuture.supplyAsync(() -> {sleep(1000);System.out.println("Thread execution - " + Thread.currentThread().getName());return "Hello-Educative";});String resultValue = completableFuture.join();System.out.println("Result - " + resultValue);}}
Explanation
- Line 1: We import the relevant packages and classes.
- Lines 5–11: We define a function called
sleep()that makes the current thread sleep for the given amount of milliseconds. - Lines 14–18: We create a
CompletableFutureusing thesupplyAsync()method by passing a supplier that sleeps for 4 seconds and returns a string value. - Line 20: We wait for the future to complete and store the result in
resultValue. - Line 22: We print the
resultValue.