A new thread pool for every request
A medium Java puzzle in the resource leaks family. One line below contains a real bug. Try to spot it first, then read why it fails and how to fix it.
Highlighted: line 5. Play this one as a puzzle without the answer.
What is wrong
Each call creates four worker threads that are never shut down. Idle non-daemon threads keep running, so the JVM accumulates thousands of threads, runs out of memory and cannot exit. Executors must be shut down or shared.
The fix
How to avoid it next time
Create thread pools once and reuse them. If a pool is local, shut it down in a finally block.
Want the background? Read Executors and thread pools in the Java concepts library.
About resource leaks
Files, streams, sockets, connections and statements hold operating system handles that the garbage collector will not release promptly. A leak often shows up only in production after hours of load as too many open files or an exhausted connection pool.
In code review: Every constructor of a closeable type should sit in a try-with-resources header. Check the exceptional path as well as the normal one.
More puzzles in this family
Frequently asked questions
What is the bug in "A new thread pool for every request"?
Each call creates four worker threads that are never shut down. Idle non-daemon threads keep running, so the JVM accumulates thousands of threads, runs out of memory and cannot exit. Executors must be shut down or shared. The faulty line is line 5: ExecutorService pool = Executors.newFixedThreadPool(4);
How do I fix it?
Replace it with: private static final ExecutorService POOL = Executors.newFixedThreadPool(4); // created once. Create thread pools once and reuse them. If a pool is local, shut it down in a finally block.
How do I catch resource leaks in code review?
Every constructor of a closeable type should sit in a try-with-resources header. Check the exceptional path as well as the normal one.
Is there a new puzzle every day?
Yes. The daily Spot the Bug puzzle picks one of these snippets for each UTC day, with the difficulty set by the weekday. Your streak is stored only in your browser.