Why Java Throws StackOverflowError Instead of OOM in Single‑Threaded Scenarios

The article explains that in Java a single thread hitting stack limits triggers StackOverflowError, while true OutOfMemoryError arises only when multiple threads exhaust the operating system's memory, and it offers practical tips to mitigate such OOM situations.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Why Java Throws StackOverflowError Instead of OOM in Single‑Threaded Scenarios

In the Java Virtual Machine specification, the JVM stack can trigger two kinds of errors: StackOverflowError when a thread requests a stack depth beyond the allowed limit, and OutOfMemoryError when the stack cannot be expanded due to insufficient memory. The native method stack behaves similarly.

The article presents a single‑threaded example using the VM argument -Xss128k that results in a StackOverflowError , demonstrating that in a single thread, memory allocation failures in the stack manifest as StackOverflowError rather than OOM.

It explains that multithreaded scenarios can lead to true OutOfMemoryError because each thread’s stack consumes a portion of the operating system‑limited process memory (e.g., 2 GB on 32‑bit Windows). Larger per‑thread stack sizes reduce the number of threads that can be created, increasing the chance of exhausting the remaining memory.

When OOM occurs due to too many threads, the usual mitigation is to reduce the maximum heap size ( -Xmx) and/or decrease the thread stack size, thereby freeing memory for additional threads.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JVMmultithreadingOutOfMemoryErrorStackOverflowErrormemory-management
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.