Course contentsShow
← Java
Lesson 2737 of 2,87050. Executor FrameworkFree lesson

When to Use submit: Tasks Requiring Monitoring or Results

Preferring submit when you need to cancel tasks, wait for completion, or retrieve results.

When to Use submit: Tasks Requiring Monitoring or Results

What you'll learn: When and why to prefer submit() over execute() for submitting tasks to an executor.


The Core Decision Point

Use submit() whenever you need to interact with a task after submission. Unlike execute(), which fires off a task and forgets about it, submit() returns a Future that acts as a handle to the running task. This handle gives you three critical capabilities that execute() cannot provide.

Three Scenarios That Demand submit

1. You need the result of the computation

When your task is a Callable that computes and returns a value, you must use submit(). The returned Future is your only way to retrieve that result via Future.get().

2. You need to cancel the task

If there's any chance you'll want to cancel a task before it completes (perhaps due to a timeout or changed requirements), submit() provides the Future.cancel() method. With execute(), once the task is running, you have no control handle.

3. You need to wait for completion or detect exceptions

Even for Runnable tasks that don't return results, submit() is valuable when you need to block until the task completes (Future.get()) or when you want to catch exceptions the task threw. Remember: execute() silently swallows exceptions, while submit() surfaces them when you call get() on the Future.

Think of It This Way

execute() is like dropping a letter in a mailbox—you trust it'll be delivered but have no way to track it or get confirmation. submit() is like sending a registered package with a tracking number—you can check its status, cancel delivery, or confirm when it arrives.

Key Takeaway:
Use submit() whenever you need to cancel tasks, wait for their completion, retrieve results, or handle exceptions—essentially any scenario requiring monitoring or interaction with the task after submission.