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;
public T join()
This method has no parameters.
This method returns the result value stored in the future.
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);}}
sleep() that makes the current thread sleep for the given amount of milliseconds.CompletableFuture using the supplyAsync() method by passing a supplier that sleeps for 4 seconds and returns a string value.resultValue.resultValue.