Skip to content
Veltoryx Technologies
ProLesson 9.7Intermediate3 min readUpdated 30 October 2026

ExecutorService and thread pools

Stop creating threads by hand. Run tasks on thread pools with ExecutorService, pick the right pool, configure ThreadPoolExecutor, and shut it down properly.

Creating a new Thread for every task is expensive and dangerous: 10,000 requests would mean 10,000 threads, and the server runs out of memory. Real applications use a thread pool: a fixed group of threads that pick tasks from a queue and are reused.

01ExecutorService basics

PoolBasics.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class PoolBasics {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(3);   // 3 reusable threads
        AtomicInteger emailsSent = new AtomicInteger();

        for (int i = 1; i <= 10; i++) {
            int orderId = i;
            pool.submit(() -> {
                // pretend to send a confirmation email for orderId
                emailsSent.incrementAndGet();
            });
        }

        pool.shutdown();                                   // accept no new tasks
        boolean finished = pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("Finished: " + finished + ", emails: " + emailsSent.get());
    }
}
Expected output
Finished: true, emails: 10

Ten tasks ran on only three threads, which were reused.

Loading the rest of the lesson…