The CompletableFuture
class in Java provides the supplyAsync()
method to run a task asynchronously and return a CompletableFuture
that holds the result of the task.
Introduction
The CompletableFuture.supplyAsync()
method is used to run a task asynchronously and return a CompletableFuture
that will be completed with the result of the task. This is useful in asynchronous programming when you need to perform non-blocking operations.
supplyAsync Method Syntax
The syntax for the supplyAsync
method is as follows:
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)
- The method takes a single parameter
supplier
of typeSupplier<U>
, which represents the task to run. - The method returns a
CompletableFuture<U>
that will be completed with the result of the task.
Examples
Example 1: Fetching Data from a Remote API
In a web application, you might want to fetch data from a remote API asynchronously to avoid blocking the main thread.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
public class FetchDataExample {
public static void main(String[] args) {
// Simulate fetching data from a remote API
CompletableFuture<String> dataFuture = CompletableFuture.supplyAsync(() -> {
// Simulate delay
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Fetched data from API";
});
// Process the fetched data
dataFuture.thenAccept(data -> System.out.println("Data: " + data));
// Wait for the task to complete
try {
dataFuture.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
Output:
Data: Fetched data from API
Example 2: Performing a Complex Calculation
In a scientific application, you might want to perform a complex calculation asynchronously to keep the UI responsive.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class ComplexCalculationExample {
public static void main(String[] args) {
// Perform a complex calculation asynchronously
CompletableFuture<Double> calculationFuture = CompletableFuture.supplyAsync(() -> {
// Simulate a complex calculation
double result = 0;
for (int i = 0; i < 1_000_000; i++) {
result += Math.sin(i) * Math.cos(i);
}
return result;
});
// Process the calculation result
calculationFuture.thenAccept(result -> System.out.println("Calculation result: " + result));
// Wait for the calculation to complete
try {
calculationFuture.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
Output:
Calculation result: -0.1272763261176061
Example 3: Task Management System
In a task management system, you might want to process tasks asynchronously to improve performance.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class TaskManagementSystem {
public static void main(String[] args) {
// Process a task asynchronously
CompletableFuture<Task> taskFuture = CompletableFuture.supplyAsync(() -> new Task("Complete project report", 2));
// Process the task result
taskFuture.thenAccept(task -> System.out.println("Processed task: " + 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:
Processed task: Complete project report (Priority: 2)
Conclusion
The CompletableFuture.supplyAsync()
method in Java is used for running tasks asynchronously and returning a CompletableFuture
that holds the result. It is particularly useful in scenarios where non-blocking operations are required, such as fetching data from a remote API, performing complex calculations, or processing tasks in a task management system.
Comments
Post a Comment
Leave Comment