Repository navigation
Expand file tree
/
Copy pathCustomerAsyncs.java
More file actions
85 lines (64 loc) · 2.68 KB
/
Copy pathCustomerAsyncs.java
File metadata and controls
85 lines (64 loc) · 2.68 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
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package modern.challenge;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
public final class CustomerAsyncs {
private static final Logger logger = Logger.getLogger(CustomerAsyncs.class.getName());
private CustomerAsyncs() {
throw new AssertionError("Cannot be instantiated");
}
private static CompletableFuture<String> fetchOrder(String customerId) {
return CompletableFuture.supplyAsync(() -> {
return "Order of " + customerId;
});
}
private static CompletableFuture<Integer> computeTotal(String order) {
return CompletableFuture.supplyAsync(() -> {
return order.length() + new Random().nextInt(1000);
});
}
private static CompletableFuture<String> packProducts(String order) {
return CompletableFuture.supplyAsync(() -> {
return "Order: " + order + " | Product 1, Product 2, Product 3, ... ";
});
}
public static void fetchOrderTotal(String customerId)
throws InterruptedException, ExecutionException {
/*
CompletableFuture<CompletableFuture<Integer>> cfTotal
= fetchOrder(customerId).thenApply(o -> computeTotal(o));
int total = cfTotal.get().get();
*/
CompletableFuture<Integer> cfTotal
= fetchOrder(customerId).thenCompose(o -> computeTotal(o));
int total = cfTotal.get();
logger.info(() -> "Total: " + total + "\n");
}
public static void deliverParcel(String order)
throws InterruptedException, ExecutionException {
CompletableFuture<String> cfParcel = computeTotal(order)
.thenCombine(packProducts(order), (total, products) -> {
return "Parcel-[" + products + " Invoice: $" + total + "]";
});
String parcel = cfParcel.get();
logger.info(() -> "Delivering: " + parcel + "\n");
}
public static CompletableFuture<String> downloadInvoices(String invoice) {
return CompletableFuture.supplyAsync(() -> {
logger.info(() -> "Downloading invoice: " + invoice);
return "Downloaded invoice: " + invoice;
});
}
public static CompletableFuture<String> raffle(String customerId) {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(new Random().nextInt(5000));
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
logger.severe(() -> "Exception: " + ex);
}
return customerId;
});
}
}