Will the JVM Exit After an OutOfMemoryError? Explanation and Handling
An OutOfMemoryError does not always terminate the JVM; the JVM exits only when all non‑daemon threads have finished or the operating system kills the process, so proper exception handling and thread management are essential to keep the application alive.
Question: Does the JVM always exit after an OOM (OutOfMemoryError) and why?
Answer: Not necessarily. The JVM will terminate only when all non‑daemon threads have exited or when an external exception causes the OS to kill the process.
Conditions for JVM exit: All non‑daemon threads have finished, or the OS forcibly kills the process.
OOM is a standard Java exception. By default, if a thread throws an OOM, that thread terminates and the stack trace is printed to the console. If every non‑daemon thread ends because of OOM (or any other exception), the JVM shuts down.
Processes are units of resource allocation, while threads are the basic units of resource scheduling.
Exception handling in the JVM is bound to threads, providing fault isolation. The following diagram illustrates this relationship:
When a Java thread throws an uncaught exception, the default java.lang.Thread.UncaughtExceptionHandler handles it. If the thread has no custom handler, the thread’s ThreadGroup provides a fallback, printing the exception stack trace to the console.
java.lang.Thread#getUncaughtExceptionHandlerThreads are valuable resources; they are usually managed via thread pools. It is important to handle exceptions yourself, preventing thread termination and avoiding the overhead of repeatedly creating new threads.
Example: Simulating an OOM where one thread exits while others continue to run.
Result:
Cognitive Technology Team
Cognitive Technology Team regularly delivers the latest IT news, original content, programming tutorials and experience sharing, with daily perks awaiting you.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.