-
Notifications
You must be signed in to change notification settings - Fork 4
/
InvoiceGenerator5_StructuredTaskScope.java
58 lines (47 loc) · 2.46 KB
/
InvoiceGenerator5_StructuredTaskScope.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
package eu.happycoders.structuredconcurrency.demo1_invoice;
import static eu.happycoders.structuredconcurrency.util.SimpleLogger.log;
import eu.happycoders.structuredconcurrency.demo1_invoice.model.Customer;
import eu.happycoders.structuredconcurrency.demo1_invoice.model.Invoice;
import eu.happycoders.structuredconcurrency.demo1_invoice.model.InvoiceTemplate;
import eu.happycoders.structuredconcurrency.demo1_invoice.model.Order;
import eu.happycoders.structuredconcurrency.demo1_invoice.service.CustomerService;
import eu.happycoders.structuredconcurrency.demo1_invoice.service.InvoiceTemplateService;
import eu.happycoders.structuredconcurrency.demo1_invoice.service.OrderService;
import java.util.concurrent.StructuredTaskScope;
import java.util.concurrent.StructuredTaskScope.Subtask;
public class InvoiceGenerator5_StructuredTaskScope {
public static void main(String[] args) throws InterruptedException {
InvoiceGenerator5_StructuredTaskScope invoiceGenerator =
new InvoiceGenerator5_StructuredTaskScope(
new OrderService(), new CustomerService(), new InvoiceTemplateService());
invoiceGenerator.createInvoice(10012, 61157, "en");
}
private final OrderService orderService;
private final CustomerService customerService;
private final InvoiceTemplateService invoiceTemplateService;
public InvoiceGenerator5_StructuredTaskScope(
OrderService orderService,
CustomerService customerService,
InvoiceTemplateService invoiceTemplateService) {
this.orderService = orderService;
this.customerService = customerService;
this.invoiceTemplateService = invoiceTemplateService;
}
Invoice createInvoice(int orderId, int customerId, String language) throws InterruptedException {
try (var scope = new StructuredTaskScope<>()) {
log("Forking tasks");
Subtask<Order> orderSubtask = scope.fork(() -> orderService.getOrder(orderId));
Subtask<Customer> customerSubtask = scope.fork(() -> customerService.getCustomer(customerId));
Subtask<InvoiceTemplate> invoiceTemplateSubtask =
scope.fork(() -> invoiceTemplateService.getTemplate(language));
log("Waiting for all tasks to finish");
scope.join();
log("Retrieving results");
Order order = orderSubtask.get();
Customer customer = customerSubtask.get();
InvoiceTemplate template = invoiceTemplateSubtask.get();
log("Generating and returning invoice");
return Invoice.generate(order, customer, template);
}
}
}