📦 What is FutureTask
?
✅ FutureTask<V>
is a class that implements both Runnable
and Future<V>
, allowing you to:
- Wrap a
Callable
orRunnable
task, - Run it in a thread or executor,
- And retrieve a result later using
Future
methods.
🔧 It’s in java.util.concurrent
public class FutureTask<V> implements RunnableFuture<V> { ... }
Where:
RunnableFuture<V>
extends bothRunnable
andFuture<V>
So a FutureTask
is:
- A task you can execute (because it’s
Runnable
) - A handle to get the result later (because it’s
Future
)
✅ Real-World Example
Callable<String> task = () -> {
Thread.sleep(1000);
return "Hello from Callable";
};
FutureTask<String> futureTask = new FutureTask<>(task);
// Run with Thread
new Thread(futureTask).start();
// Get the result
String result = futureTask.get(); // blocks until done
System.out.println(result);
🟢 Output after 1 second:
Hello from Callable
🧠 Why Use FutureTask
?
Feature | Description |
---|---|
✅ Combines Runnable + Future | Can run the task and get result |
✅ Works with Executors or Threads | Flexible execution |
✅ Can be cancelled | Via futureTask.cancel(true) |
✅ Thread-safe result caching | Only runs once, result is stored |
🔁 Common Use Cases
- Wrapping
Callable
for custom thread usage - Lazy initialization with result caching
- Manually managing task lifecycle (run, cancel, get)
- Submitting to thread pools and getting a result
📌 Bonus: Runnable
Version
You can also wrap a Runnable
with a predefined result:
Runnable runnable = () -> System.out.println("Runnable executed");
FutureTask<String> futureTask = new FutureTask<>(runnable, "Task Done");
new Thread(futureTask).start();
System.out.println(futureTask.get()); // prints: Task Done
⚠️ Notes
Caveat | Detail |
---|---|
get() blocks | Unless task is finished or timed out |
Only executes once | Even if run() is called multiple times |
Canceling is optional | You can call cancel() before/during execution |
🧠 Summary
Trait | FutureTask |
---|---|
Type | Class implementing Runnable and Future |
Use | Run task + get result later |
Works with | Threads, Executors, manually |
Handles | Callable , or Runnable + result |
Result access | Via get() , isDone() , cancel() |