Video in progress
Why should you use an ExecutorService instead of new Thread() for each task?
Creating and destroying threads is expensive, and if their number is unbounded, memory and CPU run out. An executor reuses threads, limits their number, provides a queue, and returns the result through a Future.
📖 Answer
Imagine a service that writes new Thread() for every request. Traffic grows, a few thousand threads appear, each takes memory for its stack, and the OS spends time switching between them. In the end: OutOfMemoryError: unable to create native thread.
With an executor:
ExecutorService pool = Executors.newFixedThreadPool(8);
for (Order o : orders) {
pool.submit(() -> send(o)); // anything beyond 8 waits in the queue
}
pool.shutdown();
pool.awaitTermination(1, TimeUnit.MINUTES);
What you gain:
- threads are reused;
- the degree of parallelism is explicit;
- the result and exceptions come back through a
Future; - shutdown is controlled (
shutdown).
In Java 21, with virtual threads, "one thread per task" is normal again, but that goes through an executor too: Executors.newVirtualThreadPerTaskExecutor().
Sign up to mark studied questions and save your progress.