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
| Parameter | Type | Description |
|---|---|---|
| task | Callable<T> | Runnable | The 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
trueNotes
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.