submit with Runnable: Getting Null or a Result Placeholder
What You'll Learn
You'll learn how submit(Runnable, T result) lets you specify a predetermined value that gets returned when the task completes, instead of always getting null.
The Two-Argument submit Overload
You already know that submit(Runnable) returns a Future<?> that yields null when you call get(). But there's another overload: submit(Runnable task, T result).
This version lets you provide a result placeholder—an object you supply upfront that gets returned to you when the task finishes.
How It Works
When you call submit(runnable, resultObject):
- The executor runs your
Runnabletask - When the task completes successfully, calling
Future.get()returns the exact object you passed in - If the task throws an exception,
get()still throwsExecutionExceptionas expected
Think of it like a claim ticket: You hand the executor a numbered ticket along with your task. When the task finishes, the executor hands you back that same ticket as proof of completion.
Why Use This?
The primary use case is tracking which result object corresponds to which task. For example, if you're processing multiple items, you can pass each item as its own result placeholder to know which one just completed:
ExecutorService executor = Executors.newFixedThreadPool(2);
String data = "ProcessedData";
// Submit task with result placeholder
Future<String> future = executor.submit(() -> {
// Perform work (no return value)
System.out.println("Processing...");
}, data);
// When complete, get() returns the data object we passed in
String result = future.get(); // Returns "ProcessedData"
Key Takeaway: submit(Runnable, T result) returns a Future that yields your predetermined result object upon completion, useful for identifying which task finished without converting your Runnable to a Callable.