Java Reference ยท Concurrency
The ExecutorService interface
Reference for java.util.concurrent.ExecutorService: submitting tasks, invokeAll and invokeAny, shutdown versus shutdownNow, close() and rejected tasks.
An ExecutorService runs tasks for you on threads it manages. Instead of creating a Thread for every job, you hand a Runnable or Callable to the service with submit() and get a Future back. The service decides which thread runs the task and when, which keeps the number of threads under control and separates "what to run" from "how to run it".
You normally obtain one from the Executors factory methods. The most important rule: an executor with live threads keeps the JVM running, so always shut it down. Since Java 19 ExecutorService is AutoCloseable, so a try-with-resources block does that for you.
try (ExecutorService pool = Executors.newFixedThreadPool(4)) { Future<Integer> f = pool.submit(() -> 6 * 7); System.out.println(f.get()); // 42 } // close(): stops accepting tasks and waits for the queued ones
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public interface ExecutorService extends Executor, AutoCloseable
| Method | Description |
|---|---|
void execute(Runnable) |
From Executor. Runs the task sometime later; no result, and an exception ends up in the thread's uncaught-exception handler. |
Future<T> submit(Callable<T>) |
Submits a task with a result. Exceptions are captured in the Future. |
Future<?> submit(Runnable) |
The Future completes with null. |
Future<T> submit(Runnable, T result) |
The Future completes with the given value. |
List<Future<T>> invokeAll(Collection<? extends Callable<T>>) |
Runs all tasks and returns when all are done, in input order. Overloads take a timeout. |
T invokeAny(Collection<? extends Callable<T>>) |
Returns the result of one task that completed normally and cancels the rest. |
void shutdown() |
Stops accepting new tasks; queued and running tasks still finish. Does not wait. |
List<Runnable> shutdownNow() |
Interrupts running tasks and returns the tasks that never started. |
boolean awaitTermination(long, TimeUnit) |
Waits until all tasks finish or the timeout passes. true if terminated. |
boolean isShutdown(), isTerminated() |
Lifecycle queries. |
void close() |
Java 19+. Calls shutdown() and waits for termination; interrupts and shuts down now if the waiting thread is interrupted. |
Throws: submit and execute throw RejectedExecutionException once the service is shut down (or saturated, for bounded pools) and NullPointerException for a null task. invokeAll and invokeAny throw InterruptedException; invokeAny throws ExecutionException if no task succeeds.
Usage notes
- Always shut down. Without
shutdown()orclose(), the non-daemon pool threads keep the program alive. Pools made bynewVirtualThreadPerTaskExecutor()use daemon threads, but you still wantclose()to wait for the work. - Exceptions hide in the
Future. A task passed tosubmit()that throws is silent until you callget(). Withexecute()the exception is printed by the worker thread. shutdownNow()only interrupts. A task that ignores the interrupt keeps running; write tasks that checkThread.currentThread().isInterrupted()or use interruptible calls.- Do not block pool threads waiting on other tasks of the same pool. A fixed pool of 2 whose two tasks wait for a third queued task deadlocks.
- Size pools by workload. CPU-bound work: about one thread per core. Blocking I/O: more threads, or virtual threads.
- Unbounded queues hide overload.
newFixedThreadPooluses an unbounded queue, so a fast producer can exhaust memory. Build aThreadPoolExecutorwith a bounded queue and a rejection policy when that matters. ExecutorServiceis thread-safe: any thread may submit tasks.