# ExecutorService, Thread Pools and Future

> What is ExecutorService and why use a thread pool? Explain the pool types, submit vs execute, Future, and how to shut down properly.

Canonical: https://www.internhack.in/learn/interview/java-interview/java-executorservice-thread-pools
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What is ExecutorService and why use a thread pool? Explain the pool types, submit vs execute, Future, and how to shut down properly.

## Answer

Creating a new thread for each task is like hiring a new employee every time a customer walks in, then firing them after five minutes. Thread creation costs memory (each stack is around a megabyte), OS resources and context-switching time, and an unbounded number of threads can bring a server down. A thread pool solves this by keeping a fixed group of workers alive and feeding them tasks from a queue. ExecutorService is the standard Java abstraction for that, and it decouples what to run from how and where to run it.

You obtain executors mainly through the Executors factory. newFixedThreadPool(n) has n threads and an unbounded queue, good for a predictable amount of CPU-bound work. newCachedThreadPool creates threads on demand and reuses idle ones, discarding those idle for 60 seconds; it suits many short tasks but can spawn thousands of threads under load. newSingleThreadExecutor guarantees sequential execution. newScheduledThreadPool runs delayed or periodic jobs. newWorkStealingPool uses a ForkJoinPool. And since Java 21, newVirtualThreadPerTaskExecutor gives each task a cheap virtual thread, excellent for blocking I/O.

A production note that shows depth: the Executors factories hide dangerous defaults such as unbounded queues, which can cause OutOfMemoryError when producers outrun consumers. Many style guides recommend constructing ThreadPoolExecutor directly with core size, max size, keep-alive, a bounded queue like ArrayBlockingQueue and a rejection policy. Tasks go first to core threads, then into the queue, and only when the queue is full does the pool grow up to the maximum; beyond that, the RejectedExecutionHandler applies (AbortPolicy, CallerRunsPolicy, DiscardPolicy or DiscardOldestPolicy). For sizing: CPU-bound work uses about the number of cores, while I/O-bound work can use more threads, roughly cores times (1 plus wait time over compute time).

Now execute versus submit. execute(Runnable) is fire and forget, returns void, and an uncaught exception kills that worker thread (a replacement is created). submit accepts Runnable or Callable and returns a Future. A Callable returns a result and may throw checked exceptions. The Future lets you call get, which blocks until completion, and get(timeout, unit) to bound the wait; cancel to attempt cancellation; and isDone. Crucially, exceptions thrown inside a submitted task are captured and rethrown from get wrapped in an ExecutionException, so if you never call get, the failure is silently swallowed. That is a classic bug.

For composition without blocking, use CompletableFuture: supplyAsync runs a task, thenApply transforms the result, thenCombine merges two futures, thenCompose chains dependent async calls, exceptionally or handle deal with errors, and allOf waits for many.

Shutdown is where beginners leak threads. A pool's threads are non-daemon, so if you forget to shut it down, the JVM never exits. shutdown stops accepting new tasks but lets queued ones finish. shutdownNow tries to interrupt running tasks and returns the queued ones. The recommended pattern: call shutdown, then awaitTermination with a timeout, and call shutdownNow if it expires, all in a finally block. From Java 19, ExecutorService implements AutoCloseable, so try-with-resources does this for you.

Finally, for interviews remember that tasks should respond to interruption, that ThreadLocal values can leak in pools, and that submitting a task that waits on another task in the same bounded pool can deadlock (thread starvation deadlock).

## Code examples

### Callable, Future and CompletableFuture

```
import java.util.*;
import java.util.concurrent.*;

public class ExecutorDemo {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        try {
            List<Future<Integer>> futures = new ArrayList<>();
            for (int i = 1; i <= 5; i++) {
                final int n = i;
                futures.add(pool.submit(() -> n * n));
            }
            int sum = 0;
            for (Future<Integer> f : futures) {
                sum += f.get();
            }
            System.out.println(sum);

            int answer = CompletableFuture.supplyAsync(() -> 21, pool)
                                          .thenApply(x -> x * 2)
                                          .join();
            System.out.println(answer);

            Future<?> bad = pool.submit(() -> {
                throw new IllegalStateException("boom");
            });
            try {
                bad.get();
            } catch (ExecutionException e) {
                System.out.println(e.getCause().getMessage());
            }
        } finally {
            pool.shutdown();
            pool.awaitTermination(5, TimeUnit.SECONDS);
        }
    }
}
```

Squares of 1 to 5 sum to 55. thenApply doubles 21 to 42. The exception thrown in the task surfaces from get as the cause of an ExecutionException.

## Key points

- A thread pool reuses threads and bounds concurrency; ExecutorService is the abstraction.
- Prefer ThreadPoolExecutor with a bounded queue in production instead of unbounded defaults.
- submit returns a Future and captures exceptions; execute does not.
- Always shut down: shutdown, awaitTermination, then shutdownNow.
- CompletableFuture composes async steps without blocking.

## Common follow-up questions

- What are the parameters of ThreadPoolExecutor?
- What are the rejection policies?
- Difference between Runnable and Callable?
- What are virtual threads and when would you use them?

## Interview tips

- Mention the unbounded queue risk of newFixedThreadPool; it separates textbook answers from production experience.
- Show that you always shut down executors, ideally in finally or try-with-resources.

## Concepts covered

ExecutorService, Thread Pool, Callable, Future, CompletableFuture

Previous: [Deadlock: Conditions, Detection and Prevention](https://www.internhack.in/learn/interview/java-interview/java-deadlock) · Next: [Lambdas, Functional Interfaces and Method References](https://www.internhack.in/learn/interview/java-interview/java-lambdas-functional-interfaces) · [All of Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)

## More Core Java & Collections questions

- [Streams API: Pipelines, Laziness and Collectors](https://www.internhack.in/learn/interview/java-interview/java-streams-api)
- [Optional: Purpose, Usage and Anti-Patterns](https://www.internhack.in/learn/interview/java-interview/java-optional)
- [Records in Java: Concise Immutable Data Carriers](https://www.internhack.in/learn/interview/java-interview/java-records)
- [Tricky Output Questions: Types, Overflow and Overloading](https://www.internhack.in/learn/interview/java-interview/java-tricky-output-basics)
- [Tricky Output: finally Overrides and Initialization Order](https://www.internhack.in/learn/interview/java-interview/java-tricky-output-finally-init-order)
- [JDK vs JRE vs JVM and Platform Independence](https://www.internhack.in/learn/interview/java-interview/java-jdk-jre-jvm)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [Core Java & Collections](https://www.internhack.in/learn/interview/java-interview)
