🧵 Java Callable and Future – Simple Example
💡 Overview
In Java, the Callable and Future interfaces are part of the java.util.concurrent package and provide a more powerful alternative to the traditional Runnable interface.
Both Runnable and Callable are designed for classes whose instances can be executed by another thread — but with one key difference:
| Interface | Returns Result? | Throws Checked Exception? |
|---|---|---|
Runnable | ❌ No | ❌ No |
Callable | ✅ Yes | ✅ Yes |
So, if you need a thread to return a result or throw a checked exception, Callable is the right choice.
⚙️ Key Concepts
-
CallableInterface-
Similar to
Runnable, but defines a methodcall()that can return a result and throw exceptions. -
Signature:
-
-
ExecutorService-
Manages a pool of worker threads.
-
Handles thread creation, task scheduling, and shutdown gracefully.
-
-
FutureInterface-
Represents the result of an asynchronous computation.
-
Allows you to retrieve the result using
future.get()once the task completes.
-
🧩 Example: Callable and Future in Action
1️⃣ File: CallableExample.java
🧾 Output
🧠 Explanation
-
ExecutorService creates a pool of 10 threads.
This means at most 10 threads can run concurrently. -
Each time we call
ex.submit(t1), the executor picks an available thread from the pool and runs the task. -
The
Future<String>returned bysubmit()is used to get the result fromThread1.call(). -
The output shows that threads are reused by the executor (thread-1 appears again at the end).
No comments:
Post a Comment