🎓 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 isDone() method to check if a CompletableFuture has completed.
Introduction
The CompletableFuture.isDone() method is used to check if a CompletableFuture has completed, whether normally or exceptionally. This is useful for polling the status of an asynchronous computation without blocking the calling thread.
isDone Method Syntax
The syntax for the isDone method is as follows:
public boolean isDone()
- The method does not take any parameters.
- The method returns a boolean value:
trueif theCompletableFuturehas completed,falseotherwise.
Examples
Example 1: Basic Usage
In a scenario where you have a CompletableFuture that completes with a result, you might want to check its status using the isDone() method.
import java.util.concurrent.CompletableFuture;
public class IsDoneExample {
public static void main(String[] args) {
// Create a CompletableFuture that completes with a string
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000); // Simulate delay
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Hello, world!";
});
// Check the status of the future
while (!future.isDone()) {
System.out.println("Future is not done yet...");
try {
Thread.sleep(500); // Polling delay
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Retrieve and print the result
future.thenAccept(result -> System.out.println("Result: " + result));
}
}
Output:
Future is not done yet...
Future is not done yet...
Future is not done yet...
Future is not done yet...
Result: Hello, world!
Example 2: Task Management System
In a task management system, you might want to check if a task has completed before performing a follow-up action.
import java.util.concurrent.CompletableFuture;
public class TaskManagementSystem {
public static void main(String[] args) {
// Create a CompletableFuture that completes with a task
CompletableFuture<Task> taskFuture = CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(3000); // Simulate task delay
} catch (InterruptedException e) {
e.printStackTrace();
}
return new Task("Complete project report", 2);
});
// Check the status of the task
while (!taskFuture.isDone()) {
System.out.println("Task is not done yet...");
try {
Thread.sleep(1000); // Polling delay
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Retrieve and print the task result
taskFuture.thenAccept(task -> System.out.println("Task completed: " + task));
}
}
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 is not done yet...
Task is not done yet...
Task is not done yet...
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 check if the future is done and handle the exception appropriately.
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");
});
// Check the status of the future
while (!future.isDone()) {
System.out.println("Future is not done yet...");
try {
Thread.sleep(500); // Polling delay
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 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:
Future is not done yet...
Future is not done yet...
Exception: Something went wrong
Conclusion
The CompletableFuture.isDone() method in Java is used for checking if a CompletableFuture has completed without blocking the calling thread. It is particularly useful in scenarios where you need to poll the status of an asynchronous computation, such as checking task completions, performing follow-up actions, or handling exceptions.
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