🎓 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 complete() method to manually complete a CompletableFuture with a specified value.
Introduction
The CompletableFuture.complete() method is used to manually complete a CompletableFuture with a specified value. This can be useful when you need to programmatically control the completion of a future, such as when a result is obtained from an external source.
complete Method Syntax
The syntax for the complete method is as follows:
public boolean complete(T value)
- The method takes a single parameter
valueof typeT, which is the value to complete theCompletableFuturewith. - The method returns a boolean value:
trueif theCompletableFuturewas completed as a result of this call,falseotherwise.
Examples
Example 1: Completing a CompletableFuture with a Result
In a scenario where a result is obtained from an external source, you might want to manually complete the CompletableFuture when the result is available.
import java.util.concurrent.CompletableFuture;
public class CompleteExample {
public static void main(String[] args) {
// Create a CompletableFuture
CompletableFuture<String> future = new CompletableFuture<>();
// Simulate an external source providing a result
new Thread(() -> {
try {
Thread.sleep(1000); // Simulate delay
} catch (InterruptedException e) {
e.printStackTrace();
}
future.complete("Result from external source");
}).start();
// Process the result when available
future.thenAccept(result -> System.out.println("Received result: " + result));
// Wait for the future to complete
future.join();
}
}
Output:
Received result: Result from external source
Example 2: Completing a CompletableFuture in a Task Management System
In a task management system, you might want to manually complete a CompletableFuture when a task is marked as completed.
import java.util.concurrent.CompletableFuture;
public class TaskManagementSystem {
public static void main(String[] args) {
// Create a CompletableFuture for a task
CompletableFuture<Task> taskFuture = new CompletableFuture<>();
// Simulate marking the task as completed
new Thread(() -> {
try {
Thread.sleep(1500); // Simulate task completion delay
} catch (InterruptedException e) {
e.printStackTrace();
}
taskFuture.complete(new Task("Complete project report", 2));
}).start();
// Process the completed task
taskFuture.thenAccept(task -> System.out.println("Task completed: " + task));
// Wait for the task to be completed
taskFuture.join();
}
}
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: Completing a CompletableFuture with a Default Value
In some cases, you might want to complete a CompletableFuture with a default value if the actual value is not available within a certain time frame.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class DefaultCompleteExample {
public static void main(String[] args) {
// Create a CompletableFuture
CompletableFuture<String> future = new CompletableFuture<>();
// Simulate an external source providing a result with a delay
new Thread(() -> {
try {
Thread.sleep(3000); // Simulate delay
} catch (InterruptedException e) {
e.printStackTrace();
}
future.complete("Delayed result from external source");
}).start();
// Complete the future with a default value if not completed within 2 seconds
CompletableFuture<String> resultFuture = future.completeOnTimeout("Default value", 2, TimeUnit.SECONDS);
// Process the result when available
resultFuture.thenAccept(result -> System.out.println("Received result: " + result));
// Wait for the future to complete
resultFuture.join();
}
}
Output:
Received result: Default value
Conclusion
The CompletableFuture.complete() method in Java is used for manually completing a future with a specified value. It is particularly useful in scenarios where the result is obtained from an external source, when a task is completed, or when a default value is needed. Understanding how to use this method allows for greater control and flexibility in asynchronous programming.
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