🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
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
actionof typeConsumer<? 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment