Thursday, 12 June 2025

StackOverFlowError vs OutOfMemoryError in java

 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:

public class StackOverflowExample {
public static void recursiveMethod() { recursiveMethod(); // Infinite recursion } public static void main(String[] args) { recursiveMethod(); } }
๐Ÿ’ฃ 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:

import java.util.*;
public class OutOfMemoryExample { public static void main(String[] args) { List<int[]> list = new ArrayList<>(); while (true) { list.add(new int[1_000_000]); // Keeps allocating memory } } }

Feature StackOverflowError OutOfMemoryError
Package java.lang.StackOverflowError java.lang.OutOfMemoryError
Memory Area Stack Memory (used for method calls and local variables) Heap, Metaspace, Direct Memory, or Other JVM areas
Cause Too deep or infinite recursion, or extremely large stack frames Creating too many objects, memory leaks, or excessive class loading
Common Scenario Recursive method without exit condition Adding elements endlessly to a list, loading many classes, large arrays
Thread-specific Yes (each thread has its own stack) No (shared JVM memory like heap/Metaspace)
Thrown by JVM? Yes Yes
Recoverable? Difficult; JVM will often terminate the thread Sometimes recoverable if caught and memory is freed
Can be Caught? Technically yes, but not practical Yes, but rarely useful except for logging or controlled shutdown
๐Ÿ› ️ How to Resolve Each
Resolving StackOverflowError
Action Description
๐Ÿ”„ Fix recursive logic Ensure all recursive calls have a base condition.
⬆️ Increase stack size Use JVM flag -Xss (e.g., -Xss1m) to increase stack size.
๐Ÿ”ƒ Use iteration instead of recursion For deeply recursive logic, convert recursion to iteration.
⚠️ Avoid large stack frames Don't declare huge local variables or nested method calls unnecessarily.

Resolving OutOfMemoryError

A. Java Heap Space

ActionDescription
๐Ÿงน Optimize object usageAvoid holding unnecessary objects.
๐Ÿ”„ Enable garbage collection logs-verbose:gc or use VisualVM, JConsole to monitor GC.
⬆️ Increase heap sizeUse -Xms and -Xmx (e.g., -Xmx1024m).
๐Ÿ” Use memory profilersDetect memory leaks (e.g., VisualVM, Eclipse MAT).

B. Metaspace (Java 8+)
ActionDescription
๐Ÿ“ฆ Unload classesAvoid classloader leaks (common in app servers, frameworks).
⬆️ Increase metaspaceUse -XX:MaxMetaspaceSize=256m.
๐Ÿ”„ Use shared classloadersReuse class loaders when possible.

C. GC Overhead Limit Exceeded
ActionDescription
๐Ÿ“ˆ Increase heap-Xmx to give GC more room to work.
๐Ÿง  Fix memory leaksTrack down objects not being garbage collected.
๐Ÿ’ก Optimize codeAvoid unnecessary object creation inside loops.

๐Ÿ“‚ JVM Options for Troubleshooting
OptionPurpose
-Xmx<size>Set max heap size
-Xss<size>Set stack size per thread
-XX:+HeapDumpOnOutOfMemoryErrorCreate memory dump on OOM
-verbose:gcPrint GC logs
-XX:MaxMetaspaceSize=256mLimit 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