Video in progress
In prod we got "OutOfMemoryError: unable to create native thread". What does it mean and how do you find the cause?
This is not a full heap: the OS or the container refused to create a new thread. The cause is usually a thread leak (executors that were never shut down, an unbounded cached pool), a pids or ulimit -u limit, or not enough native memory for the stacks.
📖 Answer
The first rule is not to rush to increase the heap. The error is thrown in Thread.start(), when the JVM asks the OS for a native thread. A bigger heap leaves less room for native memory and can even make things worse.
My order of checks:
# how many threads the JVM has right now
jcmd <pid> Thread.print | grep -c '^"'
ls /proc/<pid>/task | wc -l
# limits
ulimit -u # process/thread limit for the user
cat /sys/fs/cgroup/pids.max # container limit (cgroup v2)
If the thread count keeps growing over time, it's a leak. Look at the names in the dump: hundreds of pool-347-thread-1 mean someone creates Executors.newFixedThreadPool(...) on every request and never calls shutdown(). Unnamed Thread-1234 entries point to a place where new Thread() is done by hand.
Typical causes:
- creating a new executor or HTTP client on every call, and each one opens its own threads;
newCachedThreadPoolplus a slow downstream, so the thread count explodes;- a small
pidslimit in Kubernetes, which the JVM fills quickly with GC, JIT and pool threads; - a very large
-Xss, so every thread stack takes a lot of memory.
For monitoring, it's worth alerting on Micrometer's jvm.threads.live and jvm.threads.peak metrics: a leak shows up on the graph long before the error. If you have a lot of IO-heavy work, virtual threads in Java 21 are also a fix, since they don't open an OS thread for each one.
Sign up to mark studied questions and save your progress.