DEV Community

Code Green
Code Green

Posted on

What is executor service in java

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();
Enter fullscreen mode Exit fullscreen mode

Best practices

  1. Prefer ExecutorService over manually creating Threads.
  2. Always call shutdown() (or shutdownNow()) to allow JVM exit.
  3. Use bounded queues and appropriate pool sizes to avoid resource exhaustion.
  4. Use Future or CompletableFuture for result composition and cancellation handling.

Top comments (0)