In Java, working with multithreading and asynchronous programming is made much easier with the help of the java.util.concurrent
package. One of the key components in this package is the Future
interface.
If you’ve ever needed to run a task in the background and retrieve the result once it's done — without blocking your entire program — then Future
is your friend.
๐ What is Future
?
A Future
represents the result of an asynchronous computation. It acts like a placeholder for a value that will eventually be available after a long-running task completes.
In simple terms, when you submit a task to a thread pool (using an ExecutorService
), instead of immediately getting the result, you get a Future
object that promises to hold the result once the task finishes.
๐งต Why Use Future
?
-
Perform background operations without blocking the main thread.
-
Check if a task is done with
.isDone()
. -
Cancel a running task with
.cancel(true)
. -
Get the result later using
.get()
(blocks if the result isn't ready).
๐ง๐ป Basic Example: Using Future
with Callable
Here’s a beginner-friendly example showing how to use Future
in Java:
๐จ️ Output:
๐ Explanation:
✅ ExecutorService executor = Executors.newSingleThreadExecutor();
Creates a thread pool with a single thread that will run the submitted tasks.
✅ Future<Integer> future = executor.submit(...)
Submits a Callable
task (which returns a value), and returns a Future
object.
✅ future.get();
Waits for the task to complete and returns the result. If the task isn’t done yet, it blocks the current thread until it is.
✅ executor.shutdown();
Always shut down the executor to avoid memory leaks or keeping the app running unnecessarily.
๐ Additional Tips
-
future.isDone()
→ returnstrue
if the task is completed. -
future.cancel(true)
→ cancels the task if it's not finished yet. -
Callable<V>
vsRunnable
: useCallable
if you need to return a value or throw exceptions.
๐ค When Should You Use Future
?
Use Future
when you:
-
Need to perform background tasks (like file I/O or API calls).
-
Want to run multiple tasks in parallel and wait for results.
-
Want the ability to cancel a task if it’s taking too long.
๐ก Bonus: Want More Power? Try CompletableFuture
If you’re looking for even more flexibility (like chaining tasks, handling errors, async pipelines), check out CompletableFuture
. It’s the modern alternative introduced in Java 8.