Video in progress

Strong Junior ⚙️ JVM and memory

If "OutOfMemoryError: unable to create native thread" appears, does enlarging the heap help?

No, it can even hurt. This error is tied to the OS, not the heap: the stack memory for a new thread, or the number of threads allowed to the process, has run out. The cause is usually threads being created without control.

📖 Answer

Every platform thread is an OS thread. Its stack sits outside the heap. So if you raise -Xmx, the room left for stacks shrinks.

What leads to the error:

  • the OS limit: ulimit -u on Linux, the cgroup pids.max in a container;
  • the container's total memory ran out;
  • a bug in the code: new Thread(...) on every request, or creating a new Executors.newFixedThreadPool(...) each time and never calling shutdown.

The last one is the most common:

// a new pool on every call: the threads never end
void send(List<Msg> msgs) {
    ExecutorService pool = Executors.newFixedThreadPool(10);
    msgs.forEach(m -> pool.submit(() -> client.send(m)));
}

Make the pool a single one and reuse it as a bean.

To check:

jcmd <pid> Thread.print | grep -c '^"'   # the number of threads
ls /proc/<pid>/task | wc -l

If you see hundreds of threads with the same name pattern (pool-734-thread-3) in a thread dump, the cause is found. If you are on Java 21, virtual threads can also be a solution for lots of waiting I/O tasks.