Java CompletableFuture thenAccept() Method

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

Introduction

The CompletableFuture.thenAccept() method is used to process the result of a CompletableFuture once it completes. It takes a Consumer that processes the result but does not return any value.

thenAccept Method Syntax

The syntax for the thenAccept method is as follows:

public CompletableFuture<Void> thenAccept(Consumer<? super T> action)
  • The method takes a single parameter action of type Consumer<? super T>, which represents the action to perform on the result.
  • The method returns a CompletableFuture<Void> that is completed when the action is finished.

Examples

Example 1: Logging a Result

In a web application, you might want to log the result of a CompletableFuture when it completes.

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

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

        // Log the result using thenAccept
        future.thenAccept(result -> System.out.println("Received result: " + result));

        // Wait for the future to complete
        try {
            future.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

Output:

Received result: Hello, world!

Example 2: Task Management System

In a task management system, you might want to update the user interface or notify a user when a task is completed.

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));

        // Notify user when the task is completed using thenAccept
        taskFuture.thenAccept(task -> System.out.println("Task completed: " + task));

        // Wait for the task to complete
        try {
            taskFuture.get();
        } 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: Sending a Notification

In an email application, you might want to send a notification when an email is successfully sent.

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

public class EmailNotificationExample {
    public static void main(String[] args) {
        // Simulate sending an email asynchronously
        CompletableFuture<String> emailFuture = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(1000); // Simulate email sending delay
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "Email sent successfully!";
        });

        // Send a notification when the email is sent using thenAccept
        emailFuture.thenAccept(message -> System.out.println("Notification: " + message));

        // Wait for the email sending to complete
        try {
            emailFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}

Output:

Notification: Email sent successfully!

Conclusion

The CompletableFuture.thenAccept() method in Java is used for processing the result of a CompletableFuture once it completes. It is particularly useful in scenarios where you need to perform an action based on the result of an asynchronous computation, such as logging results, updating user interfaces, or sending notifications. 

Comments