Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
get
completablefuture

How to retrieve the result of a CompletableFuture in Java

abhilash

The get()method is an instance method, which is defined in the CompletableFuture class. The CompletableFuture class is defined in the java.util.concurrent package. This method indefinitely waits for the processing of the task associated with the CompletableFuture to finish and then retrieves the result.

Note: Refer to "Get the result of an asynchronous task with timeout in Java to learn how to put a timeout on the waiting period in order to retrieve the result of a CompletableFuture.

We can import the CompletableFuture class by using the following statement:

import java.util.concurrent.CompletableFuture;

Syntax


public T get()

Parameters

This method takes no parameters.

Return value

This method returns the result of the computation.

Code

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class Main {

    private static String process(){
        sleep(1000);
        System.out.println("Current Execution thread where the supplier is executed - " + Thread.currentThread().getName());
        return "Hello Educative";
    }

    private static CompletableFuture<String> createFuture(){
        return CompletableFuture.supplyAsync(Main::process);
    }

    private static void sleep(int millis){
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> stringCompletableFuture = createFuture();

        String value = stringCompletableFuture.get();

        sleep(3000);

        System.out.println("Completed Processing. Returned value - " + value);

    }
}
Implementation of the get() method

Code explanation

  • Line 1: We import the relevant packages and classes.
  • Lines 6–10: We define a function called process, which prints the thread that executes the function, sleeps for one second, and returns a string.
  • Lines 12–14: We define a function called createFuture, which uses the supplyAsync() method to run the process() method in the common pool of ForkJoinPool. This function returns a CompletableFuture.
  • Lines 16–22: We define a function called sleep(), which makes the current thread sleep for the given number of milliseconds.
  • Line 25: We invoke the createFuture method to get the CompletableFuture.
  • Line 27: We retrieve the value that is returned by the process supplier function, using the get() method .
  • Line 29: We invoke the sleep function on the main thread.
  • Line 31: We print the value that is returned by the get() method.

RELATED TAGS

java
communitycreator
get
completablefuture
RELATED COURSES

View all Courses

Keep Exploring