Commit 9d4387e
committed
feat: add ExecutorService with Callable tasks to wait for dependent services
WHAT was added:
- Implemented a Main2 class demonstrating use of ExecutorService with a fixed thread pool of 3 workers.
- Submitted three DependantServices tasks, each implementing Callable<String>.
- Each Callable prints a start message, simulates work with Thread.sleep(2000), and returns "Ok".
- Used Future<String> objects to wait for task completion via get().
- Printed a message confirming that all dependent services finished before starting main services.
- Cleanly shut down the ExecutorService.
WHY this matters:
- Shows how to use Callable instead of Runnable when tasks need to return values.
- Demonstrates waiting for multiple parallel tasks to complete before proceeding.
- Emulates a real-world scenario where dependent services (like DB, cache, API) must initialize before the main system starts.
- Reinforces proper shutdown of ExecutorService for resource management.
HOW it works:
1. A fixed thread pool of size 3 runs three DependantServices in parallel.
2. Each service prints a message and simulates work by sleeping 2 seconds.
3. Main thread calls future.get() on each Future, blocking until all tasks complete.
4. After all futures finish, prints confirmation message and shuts down executor.
NOTES and gotchas:
- future.get() is blocking; if one task takes longer, main waits until it finishes.
- Using invokeAll() could simplify submitting multiple Callable tasks at once.
- ExecutorService.shutdown() ensures no new tasks are accepted and resources are released.
- Returning "Ok" allows further aggregation or logging of service results if needed.
KEY TAKEAWAY:
- Use Callable<T> when you need tasks to return results.
- Use Future<T>.get() to block until completion and retrieve results.
- ExecutorService simplifies managing multiple parallel service initializations.
SHORT KEYS:
executorservice callable future parallel init services.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 1805dba commit 9d4387e
File tree
1 file changed
+27
-0
lines changed- Section19MultiThreading/ThreadPooling/ExecutorsFramework/ExecutorsServices/src
1 file changed
+27
-0
lines changedLines changed: 27 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 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 | + | |
0 commit comments