StackOverflowError
and OutOfMemoryError
are both critical runtime errors in Java, but they originate from different memory regions and different causes.
๐งจ 1. StackOverflowError
java.lang.StackOverflowError
occurs when the call stack (used for method calls and local variables) exceeds its limit.
๐ฅ Cause:
Typically caused by deep or infinite recursion.
๐ Example:
๐ฃ 2.
OutOfMemoryError
java.lang.OutOfMemoryError
occurs when the JVM cannot allocate memory for objects or operations because heap or other memory areas are full.
๐ฅ Causes:
-
Excessive object creation without garbage collection.
-
Memory leaks (unreferenced objects not collected).
-
Huge arrays, large images, or data.
-
Misconfigured JVM memory (-Xmx
, -XX:MaxMetaspaceSize
).
๐ Example:
A. Java Heap Space
Action Description ๐งน Optimize object usage Avoid holding unnecessary objects. ๐ Enable garbage collection logs -verbose:gc
or use VisualVM, JConsole to monitor GC.⬆️ Increase heap size Use -Xms
and -Xmx
(e.g., -Xmx1024m
). ๐ Use memory profilers Detect memory leaks (e.g., VisualVM, Eclipse MAT).
B. Metaspace (Java 8+)
Action Description ๐ฆ Unload classes Avoid classloader leaks (common in app servers, frameworks). ⬆️ Increase metaspace Use -XX:MaxMetaspaceSize=256m
. ๐ Use shared classloaders Reuse class loaders when possible.
C. GC Overhead Limit Exceeded
Action Description ๐ Increase heap -Xmx
to give GC more room to work.๐ง Fix memory leaks Track down objects not being garbage collected. ๐ก Optimize code Avoid unnecessary object creation inside loops.
๐ JVM Options for Troubleshooting
Option Purpose -Xmx<size>
Set max heap size -Xss<size>
Set stack size per thread -XX:+HeapDumpOnOutOfMemoryError
Create memory dump on OOM -verbose:gc
Print GC logs -XX:MaxMetaspaceSize=256m
Limit metaspace
๐ง Summary
Aspect
StackOverflowError
OutOfMemoryError
Memory Area
Stack
Heap, Metaspace, etc.
Main Cause
Infinite recursion
Excessive memory use
Fix
Fix recursion or increase stack
Free up memory or increase limits
Tools
Increase -Xss
, check code logic
VisualVM, -Xmx
, memory profilers
No comments:
Post a Comment