Commit 1805dba
committed
feat: demonstrate Future usage with ExecutorService.submit() and task completion check
WHAT was added:
- Created a simple Main class to showcase how to submit tasks to an ExecutorService.
- Used Executors.newSingleThreadExecutor() to create a one-thread pool.
- Submitted a lambda Runnable that prints "Hello" and captured its Future.
- Checked completion status with future.isDone() before retrieving the result.
- Retrieved task result via future.get(), which for a Runnable returns null after execution.
- Gracefully shut down the ExecutorService.
WHY this matters:
- Illustrates the difference between Runnable and Callable when used with ExecutorService.
- Shows that Future<?> from a Runnable task always yields null from get() unless a preset result is provided.
- Demonstrates non-blocking completion check with isDone() before blocking on get().
- Reinforces proper shutdown of ExecutorService to free resources.
HOW it works:
1. ExecutorService with one worker thread is created.
2. Runnable task is submitted; ExecutorService returns a Future.
3. Main thread calls future.isDone() to check completion (may still be false if checked too early).
4. future.get() blocks until task finishes, then returns null (because Runnable does not produce a result).
5. ExecutorService.shutdown() prevents new tasks and allows cleanup.
NOTES and gotchas:
- For return values, use Callable<T> instead of Runnable. Then future.get() yields the result.
- Checking future.isDone() immediately after submit often returns false because the task hasn't finished yet.
- Future.get() blocks until completion, so use isDone() or isCancelled() to check status non-blocking.
- Always shut down ExecutorService to avoid thread leakage.
- Use submit(Runnable, result) if you want a Runnable to return a specific value through Future.get().
KEY TAKEAWAY:
- Runnable + submit() → Future.get() returns null.
- Callable<T> + submit() → Future.get() returns a value.
- Always manage ExecutorService lifecycle with shutdown()/awaitTermination().
SHORT KEYS:
executorservice future runnable callable async-task.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 8350b53 commit 1805dba
File tree
1 file changed
+17
-0
lines changed- Section19MultiThreading/ThreadPooling/ExecutorsFramework/ExecutorsServices/src
1 file changed
+17
-0
lines changedLines changed: 17 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 | + | |
0 commit comments