import java.util.concurrent.CompletableFuture;
public class OrderPipeline {
public static void main(String[] args) {
int orderId = 101;
System.out.println("Starting order pipeline...");
// 1. Build the pipeline chain
CompletableFuture<Void> pipeline = CompletableFuture.supplyAsync(() -> fetchOrder(orderId))
.thenApply(order -> processPayment(order)) // Transform Order -> Payment
.thenApply(payment -> generateInvoice(payment)) // Transform Payment -> String (Invoice)
.thenAccept(invoice -> System.out.println(invoice)); // Consume String
// 2. Wait for completion
// We use join() to block the main thread until the entire chain finishes.
pipeline.join();
System.out.println("Main thread finished.");
}
// --- Helper Methods ---
static Order fetchOrder(int id) {
System.out.println("1. Fetching Order #" + id + "...");
sleep(500);
return new Order(id, 150.00);
}
static Payment processPayment(Order order) {
System.out.println("2. Processing Payment for Order #" + order.id + "...");
sleep(500);
return new Payment(order, "PAID-" + System.currentTimeMillis());
}
static String generateInvoice(Payment payment) {
System.out.println("3. Generating Invoice...");
sleep(500);
return "INVOICE: Order " + payment.order.id + " | Amount $" + payment.order.amount + " | Status: " + payment.transactionId;
}
static void sleep(int ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
record Order(int id, double amount) {}
record Payment(Order order, String transactionId) {}
}