Video in progress

Strong Junior 🧵 Concurrency

What are the hidden dangers of Executors.newFixedThreadPool and newCachedThreadPool?

A fixed pool uses an unbounded LinkedBlockingQueue, so if load grows, the queue grows without limit and memory runs out. A cached pool doesn't limit the thread count, so it opens a new thread for every new task and can choke the OS.

📖 Answer

Both are ready-made ThreadPoolExecutor configurations:

Factory Threads Queue When load grows
newFixedThreadPool(n) exactly n unbounded LinkedBlockingQueue tasks pile up in memory
newCachedThreadPool() from 0 to Integer.MAX_VALUE SynchronousQueue (no capacity) the thread count explodes

A real case: requests to an external API went through a fixed pool. The API slowed down, millions of tasks piled up in the queue, and the heap ran out. Only an OutOfMemoryError was left in the log.

That is why on prod I create the executor by hand, with limits:

ExecutorService pool = new ThreadPoolExecutor(
        8, 16,
        60, TimeUnit.SECONDS,
        new ArrayBlockingQueue<>(1_000),          // bounded queue
        Thread.ofPlatform().name("mail-", 0).factory(),
        new ThreadPoolExecutor.CallerRunsPolicy() // when full, the caller runs it itself
);

You decide what happens when the queue is full: reject, slow the caller down, or drop. That is backpressure.