-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompletableFutureChainExample.java
More file actions
35 lines (28 loc) · 1.41 KB
/
CompletableFutureChainExample.java
File metadata and controls
35 lines (28 loc) · 1.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
public class CompletableFutureChainExample {
public static void main(String[] args) {
// Use a custom thread pool for demonstration
var executor = Executors.newFixedThreadPool(2);
// 1. Initial task: Supply a result asynchronously
CompletableFuture<String> initialTask = CompletableFuture.supplyAsync(() -> {
System.out.println("Step 1: Fetching user ID in " + Thread.currentThread().getName());
return "user123";
}, executor);
// 2. Chain 1: Transform the result (user ID to data URL)
CompletableFuture<String> dataUrlFuture = initialTask.thenApplyAsync(userId -> {
System.out.println("Step 2: Generating URL in " + Thread.currentThread().getName());
return "http://api.data.com/" + userId;
}, executor);
// 3. Chain 2: Process the final result (print it)
dataUrlFuture.thenAccept(finalUrl -> {
System.out.println("Step 3: Final data URL is " + finalUrl + " in " + Thread.currentThread().getName());
});
System.out.println("Main thread is not blocked.");
// Wait for all tasks to complete (in a real app, you'd manage the ExecutorService better)
executor.shutdown();
while (!executor.isTerminated()) {
// Wait for completion
}
}
}