ExecutorService in Java
ExecutorService is a high-level interface in java.util.concurrent that represents an asynchronous execution service which accepts tasks (Runnable or Callable) and manages a pool of threads to run them. It decouples task submission from task execution and provides lifecycle control and result/future handling.
Key responsibilities
- Accept tasks via submit/execute.
- Manage worker threads (thread pooling).
- Return Future objects for monitoring results/cancellation.
- Support orderly shutdown and termination waiting.
- Optionally schedule tasks when using ScheduledExecutorService (sub-interface).
Important methods
- execute(Runnable task) — submit a task without a result.
- Future submit(Callable task) — submit a task that returns a result.
- Future<?> submit(Runnable task) — submit Runnable and get Future for cancellation.
- List> invokeAll(Collection<? extends Callable> tasks) — run tasks and wait for all.
- T invokeAny(Collection<? extends Callable> tasks) — run tasks and return one successful result.
- shutdown() — start orderly shutdown (no new tasks).
- List shutdownNow() — attempt to stop executing tasks and return pending tasks.
- boolean isShutdown(), boolean isTerminated(), awaitTermination(long timeout, TimeUnit unit).
Common implementations / providers
- Executors.newFixedThreadPool(n) — fixed-size pool (returns ExecutorService).
- Executors.newCachedThreadPool() — dynamically-sized pool.
- Executors.newSingleThreadExecutor() — single-threaded executor.
- ThreadPoolExecutor — configurable concrete implementation.
- ScheduledThreadPoolExecutor — implements ScheduledExecutorService for delayed/periodic tasks.
Example
ExecutorService executor = Executors.newFixedThreadPool(4);
Future<Integer> future = executor.submit(() -> {
// do work
return 42;
});
int result = future.get(); // blocks until done
executor.shutdown();
Best practices
- Prefer ExecutorService over manually creating Threads.
- Always call
shutdown()(orshutdownNow()) to allow JVM exit. - Use bounded queues and appropriate pool sizes to avoid resource exhaustion.
- Use Future or CompletableFuture for result composition and cancellation handling.
Top comments (0)