SoFunction
Updated on 2025-04-27

JAVA Focus OutOfMemoryError Exception Problem Record

In Java development, memory overflow exceptions are a key issue affecting program stability. Understanding its principles and coping methods is crucial to developers.

1. Java heap overflow

principle

The Java heap is used to store object instances. Continuously create objects and prevent garbage collector from recycling. When the number of objects exceeds the heap capacity, heap overflow will be caused.

Sample code

// VM Args: -Xmx20m -Xms20m -XX:+HeapDumpOnOutOfMemoryError
public class HeapOOM {
    static class OOMObject {}
    public static void main(String[] args) {
        List<OOMObject> list = new ArrayList<>();
        while (true) {
            (new OOMObject());
        }
    }
}

Solution

  • Use memory image analysis tools such as Eclipse Memory Analyzer to analyze heap dump snapshots.
  • Differentiate between memory leaks and memory overflows: If useless objects occupy memory for a long time, it is a memory leak; if the objects are useful but the heap space is insufficient, the heap parameters (-Xmx and - Xms) can be adjusted, and the code can be optimized to reduce memory usage.

2. Virtual machine stack and local method stack overflow

principle

  • Thread request stack depth exceeds the allowed value of the virtual machine, throw*Error 。
  • If the virtual machine stack supports dynamic expansion, the memory application fails during expansion and is thrown.OutOfMemoryError(HotSpot does not support stack dynamic expansion).

Sample code

test*Error

// VM Args: -Xss128k
public class JavaVMStackSOF {
    private int stackLength = 1;
    public void stackLeak() {
        stackLength++;
        stackLeak();
    }
    public static void main(String[] args) throws Throwable {
        JavaVMStackSOF oom = new JavaVMStackSOF();
        try {
            ();
        } catch (Exception e) {
            ("stack length:" + );
            throw e;
        }
    }
}

Testing a large number of threads causing memory overflow

// VM Args: -Xss2M
public class JavaVMStackOOM {
    private void dontStop() {
        while (true) {}
    }
    public void stackLeakByThread() {
        while (true) {
            Thread thread = new Thread(() -> dontStop());
            ();
        }
    }
    public static void main(String[] args) throws Throwable {
        JavaVMStackOOM oom = new JavaVMStackOOM();
        ();
    }
}

Solution

  • Appear*ErrorWhen , you can analyze recursive calls and other problem codes based on the error stack.
  • For memory overflows caused by large numbers of threads, you can reduce the number of threads, adjust the stack memory size (-Xss), or upgrade a 64-bit virtual machine to get more memory.

3. Method area and runtime constant pool overflow

principle

  • The method area stores class information, constant pools, etc. Dynamically generates a large number of classes (such as using CGLib) at runtime, which will exhaust the method area space.
  • The constant pool is part of the method area and string operations (such as()) Improper, which may cause constant pool overflow.

Sample code

Method area overflow test (with CGLib)

// VM Args: -XX:PermSize=10M -XX:MaxPermSize=10M
import ;
import ;
import ;
public class JavaMethodAreaOOM {
    static class OOMObject {}
    public static void main(String[] args) {
        while (true) {
            Enhancer enhancer = new Enhancer();
            ();
            (false);
            (new MethodInterceptor() {
                @Override
                public Object intercept(Object obj,  method, Object[] args, MethodProxy proxy) throws Throwable {
                    return (obj, args);
                }
            });
            ();
        }
    }
}

Runtime constant pool overflow test (()

// JDK 6 run: -XX:PermSize=6M -XX:MaxPermSize=6M// JDK 7 and above runs: -Xmx6Mpublic class RuntimeConstantPoolOOM {
    public static void main(String[] args) {
        String str1 = new StringBuilder("computer").append("software").toString();
        (() == str1); 
        String str2 = new StringBuilder("ja").append("va").toString();
        (() == str2); 
    }
}

Solution

  • When the method area overflows, adjust the relevant parameters of the method area (such as - XX:PermSize and - XX:MaxPermSize before JDK 8, JDK 8 and later - XX:MetaspaceSize, etc.), and optimize the code to reduce dynamic class generation.
  • For constant pool overflow, use reasonably()Method to avoid meaningless strings into the pool operation.

4. Direct memory overflow

principle

Direct memory capacity is-XX:MaxDirectMemorySizeParameter control, default is the same as the Java heap maximum. Direct or indirect useDirectByteBufferUnsafeIf the allocated memory exceeds the limit, it will cause an overflow.

Sample code

// VM Args: -Xmx20M -XX:MaxDirectMemorySize=10M
import ;
import ;
public class DirectMemoryOOM {
    private static final int _1MB = 1024 * 1024;
    public static void main(String[] args) throws Exception {
        Field unsafeField = ()[0];
        (true);
        Unsafe unsafe = (Unsafe) (null);
        while (true) {
            (_1MB);
        }
    }
}

Solution

  • Reasonable setting-XX:MaxDirectMemorySizeparameter.
  • Troubleshoot direct memory allocation operations in the code, such as NIO-related code, to ensure reasonable memory allocation.
(null);
while (true) {
(_1MB);
}
}
}

Solution

- Reasonably set the `-XX:MaxDirectMemorySize` parameter.
- Troubleshoot direct memory allocation operations in the code, such as NIO-related code, to ensure reasonable memory allocation.

By deeply understanding the principle of Java memory overflow exceptions, combined with specific code examples and solutions, developers can better locate and solve memory problems and ensure the stable operation of Java programs.

This is the article about JAVA focusing on the records of OutOfMemoryError Exception Problem. This is all about this article. For more related java OutOfMemoryError exception content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!