Executors and thread pools question 80 of 180 mid
Why is Executors.newFixedThreadPool considered dangerous in production?
- It creates too many threads
- Correct: Its queue is unbounded, so a backlog grows until the heap is gone instead of pushing back
- It never shuts down
- It uses daemon threads
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
);
Quiz yourself on Executors and thread pools Suggest a correction