The submit Method: Returning a Future
You'll learn how the submit() method differs from execute() by returning a Future object that lets you track task progress and retrieve results.
Why submit() Exists
While execute() is "fire-and-forget," sometimes you need to know when a task finishes or what result it produces. The submit() method solves this by returning a Future object—think of it as a claim ticket at a coat check. You hand in your task, get a ticket back, and later use that ticket to retrieve the result or check if your task is done.
How It Works
The ExecutorService interface provides two key overloads:
-
submit(Runnable task)– Submits aRunnable(no return value) and returns aFuture<?>. You can use thisFutureto detect completion, but callingget()on it returnsnull. -
submit(Callable<V> task)– Submits aCallable(returns a result of typeV) and returns aFuture<V>. ThisFuturelets you retrieve the actual result when the task completes.
The Power of Future
Once you have a Future object, you can:
- Check if the task is done with
isDone() - Wait for completion and get the result with
get()(blocks until ready) - Cancel the task if needed
This transforms asynchronous execution from "fire-and-forget" into "fire-and-track."
Real Benefit
Unlike execute(), which gives you no handle on submitted work, submit() provides a reference point. You submit your task, continue doing other work, and later circle back to collect the result or verify completion—all without manual thread coordination.
Key Takeaway: submit() returns a Future object that acts as a handle to your submitted task, enabling you to track completion and retrieve results from both Runnable and Callable tasks.