Java CompletableFuture get() Method

The CompletableFuture class in Java provides the get() method to retrieve the result of a CompletableFuture when it completes.

Introduction

The CompletableFuture.get() method is used to retrieve the result of a CompletableFuture once it completes. It blocks the calling thread until the future is complete, making it useful for waiting for the result of asynchronous computations.

get Method Syntax

The syntax for the get method is as follows:

public T get() throws InterruptedException, ExecutionException
  • The method does not take any parameters.
  • The method returns the result of the CompletableFuture.
  • The method throws:
    • InterruptedException if the current thread was interrupted while waiting.
    • ExecutionException if the computation threw an exception.

Examples

Example 1: Basic Usage

In a scenario where you have a CompletableFuture that completes with a result, you might want to retrieve the result using the get() method.

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

public class GetExample {
    public static void main(String[] args) {
        // Create a CompletableFuture that completes with a string
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello, world!");

        // Retrieve the result using get
        try {
            String result = future.get();
            System.out.println("Result: " + result);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

Output:

Result: Hello, world!

Example 2: Task Management System

In a task management system, you might want to retrieve the result of a task once it completes.

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

public class TaskManagementSystem {
    public static void main(String[] args) {
        // Create a CompletableFuture that completes with a task
        CompletableFuture<Task> taskFuture = CompletableFuture.supplyAsync(() -> new Task("Complete project report", 2));

        // Retrieve the result using get
        try {
            Task task = taskFuture.get();
            System.out.println("Task completed: " + task);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

class Task {
    private String description;
    private int priority;

    public Task(String description, int priority) {
        this.description = description;
        this.priority = priority;
    }

    @Override
    public String toString() {
        return description + " (Priority: " + priority + ")";
    }
}

Output:

Task completed: Complete project report (Priority: 2)

Example 3: Handling Exceptions

In an application where an exception might be thrown during the asynchronous computation, you can handle the exception using the get() method.

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

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        // Create a CompletableFuture that throws an exception
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            throw new RuntimeException("Something went wrong");
        });

        // Retrieve the result using get and handle the exception
        try {
            String result = future.get();
            System.out.println("Result: " + result);
        } catch (InterruptedException e) {
            System.out.println("Thread was interrupted");
        } catch (ExecutionException e) {
            System.out.println("Exception: " + e.getCause().getMessage());
        }
    }
}

Output:

Exception: Something went wrong

Conclusion

The CompletableFuture.get() method in Java is used for retrieving the result of a CompletableFuture once it completes. It is particularly useful in scenarios where you need to wait for the result of an asynchronous computation, handle task completions, or manage exceptions.

Comments