Commit f68f983
committed
feat(completablefuture): add demo for async tasks with timeout and exception handling
What
- Introduced `CompletableFutureDemo` to demonstrate advanced usage of Java’s `CompletableFuture`.
- Implemented:
- Parallel execution of two async tasks:
- `fetchUserDetails()` → simulates network call for user profile.
- `fetchOrderHistory()` → simulates network call for user orders (with random failure).
- Combination of results using `thenCombine()` to merge outputs when both tasks finish.
- Timeout handling with `applyToEither()` and a helper `timeoutAfter()` future.
- Exception handling with `exceptionally()` to provide a safe fallback message.
- Final result is printed to console with either combined data, timeout message, or error details.
Why
- Showcases **asynchronous programming** in Java without blocking threads.
- Demonstrates:
- Running multiple tasks concurrently (`supplyAsync`).
- Combining dependent async results (`thenCombine`).
- Handling unpredictable delays (`timeoutAfter`).
- Managing failures gracefully (`exceptionally`).
- Provides a practical pattern for resilient, fault-tolerant microservice or API calls.
Logic
1. **Task Creation**
- `CompletableFuture.supplyAsync()` runs tasks in ForkJoinPool common pool threads.
- Two tasks:
- `fetchUserDetails()` → sleeps 1s, returns user string.
- `fetchOrderHistory()` → sleeps 1.5s, randomly fails 30% of the time.
2. **Result Combination**
- `thenCombine(userFuture, orderFuture, ...)` merges results once both complete.
- Produces a formatted output containing both user and order data.
3. **Timeout Handling**
- `timeoutAfter(2)` starts another async future that waits 2s before returning `"Request timed out!"`.
- `applyToEither(combinedFuture, timeoutFuture)` ensures whichever completes first is used.
- Prevents hanging if services are too slow.
4. **Exception Handling**
- `exceptionally(ex -> "Error fetching data: ...")` ensures program never crashes.
- Converts runtime exceptions (like service failure) into safe user-facing messages.
5. **Final Execution**
- `join()` waits for result, returning either:
- Successful combined data,
- Timeout message,
- Or error fallback.
Real-life applications
- Microservices orchestration: Fetching data from multiple APIs in parallel with timeouts.
- E-commerce systems: Get user profile + order/cart details concurrently.
- Mobile/Frontend backends: Aggregate slow services without blocking UI.
- Fault-tolerant distributed systems: Ensure safe defaults when some services fail.
Notes
- Default async execution uses ForkJoinPool’s common pool; can supply custom executors for better scaling.
- `applyToEither()` races futures → useful for fallback/timeout patterns.
- Always handle exceptions (`exceptionally` or `handle`) in production-grade async flows.
- Random failure in `fetchOrderHistory()` mimics real-world flaky services.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 7c82386 commit f68f983
File tree
1 file changed
+36
-35
lines changed- Java 8 Crash Course/Completable Future/src
1 file changed
+36
-35
lines changedLines changed: 36 additions & 35 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
| 3 | + | |
4 | 4 | | |
5 | 5 | | |
6 | 6 | | |
| |||
23 | 23 | | |
24 | 24 | | |
25 | 25 | | |
26 | | - | |
| 26 | + | |
27 | 27 | | |
28 | 28 | | |
29 | 29 | | |
| |||
50 | 50 | | |
51 | 51 | | |
52 | 52 | | |
| 53 | + | |
| 54 | + | |
53 | 55 | | |
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 | | - | |
86 | | - | |
| 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 | + | |
| 86 | + | |
| 87 | + | |
0 commit comments