Java Concurrency Interview

Executors and thread pools question 80 of 180 mid

Why is Executors.newFixedThreadPool considered dangerous in production?

newFixedThreadPool and newSingleThreadExecutor both use an unbounded queue. When producers outrun consumers, nothing pushes back: the queue grows, old GC pressure rises, and the process dies with an OutOfMemoryError whose stack trace points at the queue rather than at the real cause.

newCachedThreadPool has the opposite failure. Its SynchronousQueue has no capacity and its maximum is Integer.MAX_VALUE, so a burst creates a thread per task until the OS refuses.

The production shape is to build the executor yourself:

new ThreadPoolExecutor(8, 8, 60, SECONDS,
        new ArrayBlockingQueue<>(1000),           // bounded: backpressure
        new NamedThreadFactory("api-"),           // named: readable thread dumps
        new ThreadPoolExecutor.CallerRunsPolicy() // slow the producer down
);

executors backpressure

Quiz yourself on Executors and thread pools Suggest a correction