What does 'result' in ExecutorService.submit(Runnable task, T result) do?

It doesn't do anything with the result - just holds it. When the task successfully completes, calling future.get() will return the result you passed in.

Here is the source code of Executors$RunnableAdapter, which shows that after the task has run, the original result is returned:

static final class RunnableAdapter<T> implements Callable<T> {
    final Runnable task;
    final T result;
    RunnableAdapter(Runnable  task, T result) {
        this.task = task;
        this.result = result;
    }
    public T call() {
        task.run();
        return result;
    }
}

And yes, the generic type of the result should match that of the returned Future.


Runnable does not return anything and Future must return something so this method allows you to predefine the result of the returned future.

If you don't want to return a thing you can return null and I think the Void type exists to express that kind of things.

Future<Void> myFuture = executor.submit(myTask, null);

You know myFuture.get() will return null in this case but only after the task has been run, so you would use it to wait and throw any exception that were thrown in the task.

try {
  myFuture.get();
  // After task is executed successfully
  ...
} catch (ExecutionException e) {
  Throwable c = e.getCause();
  log.error("Something happened running task", c);
  // After task is aborted by exception
  ...
}

You can mutate the object that was passed-in during the task. For example:

final String[] mutable = new String[1];
Runnable r = new Runnable() {
    public void run() {
        mutable[0] = "howdy";
    }
};
Future<String[]> f = executorService.submit(r, mutable);
String[] result = f.get();
System.out.println("result[0]: " + result[0]);

When I run this code it outputs:

result[0]: howdy