Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

ExecutorService.submit()

Sends a task to the pool and immediately returns a `Future` for its result.

Available since: Java 1.5

Syntax

<T> Future<T> submit(Callable<T> task)
Future<?> submit(Runnable task)

Parameters

ParameterTypeDescription
taskCallable<T> | RunnableThe task: a `Callable` returns a result, a `Runnable` does not.

Return value

Future<T>An object for getting the result later.

Examples

A task with a result and one without:

void main() throws Exception {
    try (var pool = Executors.newFixedThreadPool(2)) {
        Future<String> greeting = pool.submit(() -> "Hello from the pool");
        Future<?> job = pool.submit(() -> IO.println("side job"));
        job.get();
        IO.println(greeting.get());
        IO.println(job.isDone());
    }
}

Output:

side job
Hello from the pool
true

Notes

A lambda that returns a value becomes a Callable, a lambda without a result becomes a Runnable. A Callable may throw checked exceptions; they arrive at Future.get() wrapped in ExecutionException. For a group of tasks there is invokeAll().

See also

  • Future.get() — Waits for a task to finish and returns its result.
  • ExecutorService — A service that runs tasks on a pool of threads.
  • Runnable — A task with no arguments and no result.

Related recipes

In the tutorial

  • Thread pools and ExecutorService — ExecutorService in Java — thread pools, submit, Callable and Future, invokeAll, handling errors in tasks, timeouts and closing the pool.

Thanks for reading!

Donate to the site — we work hard for you.