-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathMultiApiDataFetcher.java
64 lines (51 loc) · 2.09 KB
/
MultiApiDataFetcher.java
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.javatechie.async;
import java.util.concurrent.CompletableFuture;
public class MultiApiDataFetcher {
public CompletableFuture<String> fetchWeatherData() {
return CompletableFuture.supplyAsync(() -> {
simulateDelay(2000); // Simulate network delay
return "Weather: Sunny, 25°C";
});
}
public CompletableFuture<String> fetchNewsHeadlines() {
return CompletableFuture.supplyAsync(() -> {
simulateDelay(3000); // Simulate network delay
return "News: Java 23 Released!";
});
}
public CompletableFuture<String> fetchStockPrices() {
return CompletableFuture.supplyAsync(() -> {
simulateDelay(1500); // Simulate network delay
return "Stocks: AAPL - $150, GOOGL - $2800";
});
}
private void simulateDelay(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
MultiApiDataFetcher fetcher = new MultiApiDataFetcher();
//combine multiple independent future (more than 2) -> allOf(n task)
//-> weatherDetailsAPI
CompletableFuture<String> weatherFuture = fetcher.fetchWeatherData();
//-> news apis
CompletableFuture<String> newsFuture = fetcher.fetchNewsHeadlines();
//-> stockPrice apis
CompletableFuture<String> stockPriceFuture = fetcher.fetchStockPrices();
//wait for all future to complete
CompletableFuture<Void> allFutures = CompletableFuture.allOf(weatherFuture, newsFuture, stockPriceFuture);
//process results after all future are completed
allFutures.thenRun(() -> {
String weather = weatherFuture.join();
String news = newsFuture.join();
String stock = stockPriceFuture.join();
System.out.println("Aggregated Data : ");
System.out.println(weather);
System.out.println(news);
System.out.println(stock);
}).join();
}
}