The CompletableFuture
class in Java provides the completeExceptionally()
method to complete a CompletableFuture
with an exception.
Introduction
The CompletableFuture.completeExceptionally()
method is used to complete a CompletableFuture
with an exception. This can be useful when you need to signal that an error has occurred in an asynchronous computation.
completeExceptionally Method Syntax
The syntax for the completeExceptionally
method is as follows:
public boolean completeExceptionally(Throwable ex)
- The method takes a single parameter
ex
of typeThrowable
, which is the exception to complete theCompletableFuture
with. - The method returns a boolean value:
true
if theCompletableFuture
was completed as a result of this call,false
otherwise.
Examples
Example 1: Handling an Exception in an Asynchronous Task
In a scenario where an exception occurs during an asynchronous task, you might want to complete the CompletableFuture
with the exception.
import java.util.concurrent.CompletableFuture;
public class CompleteExceptionallyExample {
public static void main(String[] args) {
// Create a CompletableFuture
CompletableFuture<String> future = new CompletableFuture<>();
// Simulate an asynchronous task that encounters an exception
new Thread(() -> {
try {
Thread.sleep(1000); // Simulate delay
throw new RuntimeException("Error occurred during task execution");
} catch (Exception e) {
future.completeExceptionally(e);
}
}).start();
// Handle the result or exception
future.whenComplete((result, ex) -> {
if (ex != null) {
System.out.println("Exception: " + ex.getMessage());
} else {
System.out.println("Result: " + result);
}
});
// Wait for the future to complete
future.join();
}
}
Output:
Exception: Error occurred during task execution
Example 2: Task Management System
In a task management system, you might want to complete a CompletableFuture
with an exception if a task fails to complete successfully.
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 processing a task that encounters an exception
new Thread(() -> {
try {
Thread.sleep(1500); // Simulate task processing delay
throw new RuntimeException("Failed to complete the task");
} catch (Exception e) {
taskFuture.completeExceptionally(e);
}
}).start();
// Handle the completed task or exception
taskFuture.whenComplete((task, ex) -> {
if (ex != null) {
System.out.println("Task failed: " + ex.getMessage());
} else {
System.out.println("Task completed: " + task);
}
});
// Wait for the task to complete
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 failed: Failed to complete the task
Example 3: Network Request Handling
In an application that makes network requests, you might want to complete a CompletableFuture
with an exception if the request fails.
import java.util.concurrent.CompletableFuture;
public class NetworkRequestExample {
public static void main(String[] args) {
// Create a CompletableFuture for a network request
CompletableFuture<String> requestFuture = new CompletableFuture<>();
// Simulate a network request that encounters an exception
new Thread(() -> {
try {
Thread.sleep(2000); // Simulate network delay
throw new RuntimeException("Network request failed");
} catch (Exception e) {
requestFuture.completeExceptionally(e);
}
}).start();
// Handle the result or exception
requestFuture.whenComplete((response, ex) -> {
if (ex != null) {
System.out.println("Request failed: " + ex.getMessage());
} else {
System.out.println("Response: " + response);
}
});
// Wait for the request to complete
requestFuture.join();
}
}
Output:
Request failed: Network request failed
Conclusion
The CompletableFuture.completeExceptionally()
method in Java is used for completing a future with an exception. It is particularly useful in scenarios where you need to signal an error in asynchronous computations, such as handling exceptions in asynchronous tasks, task management systems, or network request handling.
Comments
Post a Comment
Leave Comment