Java.Multithreading.What is FutureTask?

📦 What is FutureTask?

FutureTask<V> is a class that implements both Runnable and Future<V>, allowing you to:

  • Wrap a Callable or Runnable 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 both Runnable and Future<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?

FeatureDescription
✅ Combines Runnable + FutureCan run the task and get result
✅ Works with Executors or ThreadsFlexible execution
✅ Can be cancelledVia futureTask.cancel(true)
✅ Thread-safe result cachingOnly 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

CaveatDetail
get() blocksUnless task is finished or timed out
Only executes onceEven if run() is called multiple times
Canceling is optionalYou can call cancel() before/during execution

🧠 Summary

TraitFutureTask
TypeClass implementing Runnable and Future
UseRun task + get result later
Works withThreads, Executors, manually
HandlesCallable, or Runnable + result
Result accessVia get(), isDone(), cancel()
This entry was posted in Без рубрики. Bookmark the permalink.