SoFunction
Updated on 2025-05-08

Analysis and resolution of Java memory area and memory overflow exceptions

In Java development, memory management and memory overflow exceptions (OfMemoryError) are a crucial topic. The memory area of ​​a Java virtual machine (JVM) is divided into multiple parts, each with its specific purpose and limitations. When the memory in these areas is exhausted, a memory overflow exception is triggered. This article will explore the memory area of ​​Java and its corresponding memory overflow exceptions in depth, and help you better understand and deal with these problems through code examples.

1. Overview of Java memory area

1.1 Program Counter Register

The program counter is the line number indicator of the bytecode executed by the current thread. It does not have memory overflow issues.

1.2 Java Virtual Machine Stacks

Each thread has a private virtual machine stack, which is used to store information such as local variables, operand stacks, etc. during method call.

Stack Overflow Scene

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 (Throwable e) {
            ("stack length: " + );
            throw e;
        }
    }
}

Running results:

stack length: 2402
Exception in thread "main"

1.3 Native Method Stacks

The local method stack is similar to the virtual machine stack, but is used to store the call information of a local method (Native method).

1.4 Java Heap (Java Heap)

The Java heap is a memory area shared by all threads and is used to store object instances and arrays.

Heap overflow scene

import ;

public class HeapOOM {
    static class OOMObject {}

    public static void main(String[] args) {
        ArrayList<OOMObject> list = new ArrayList<>();
        while (true) {
            (new OOMObject());
        }
    }
}

Running results:

Exception in thread "main" : Java heap space

1.5 Method Area

The method area is used to store the structure information, constant pools, method data, etc. of the class.

Method area overflow scenario

import ;
import ;

public class MethodAreaOOM {
    public static void main(String[] args) {
        List<Class<?>> list = new ArrayList<>();
        int i = 0;
        while (true) {
            (new MyClassLoader().findClass("" + i++));
        }
    }

​​​​​​​    static class MyClassLoader extends ClassLoader {
        @Override
        protected Class<?> findClass(String name) {
            byte[] b = new byte[0];
            return defineClass(name, b, 0, );
        }
    }
}

Running results:

Exception in thread "main" : Metaspace

1.6 Direct Memory

The native direct memory is used for direct memory operations, usually used by ByteBuffer.

Direct memory overflow scenario

import ;

public class DirectMemoryOOM {
    private static final int _1MB = 1024 * 1024;

    public static void main(String[] args) {
        try {
            while (true) {
                (_1MB);
            }
        } catch (Throwable e) {
            ();
        }
    }
}

Running results:

Exception in thread "main" : Direct buffer memory

2. Memory overflow exception and its solution

2.1 Java heap overflow

reason

The Java heap is used to store object instances. When objects are constantly created and there is an accessible path between GC Roots and objects, the heap memory exhaustion will raise an OutOfMemoryError.

Solution

  • Use memory image analysis tools such as Eclipse Memory Analyzer to analyze heap dump snapshots to determine if they are memory leaks or memory overflows.
  • Adjust virtual machine heap parameters (-Xmx and -Xms).
  • Optimize code, reduce unnecessary object references, and shorten object life cycle.

2.2 Virtual machine stack and local method stack overflow

reason

A *Error is raised if the stack depth requested by a thread exceeds the maximum depth allowed by the virtual machine; if sufficient memory cannot be applied for when dynamically expanding the stack, an OutOfMemoryError is raised.

Solution

  • Adjust stack size parameter (-Xss).
  • Optimize recursive algorithms to reduce stack depth.

2.3 Method area overflow

reason

The method area stores the structure information of the class and dynamically generates a large number of classes (such as using CGLib) will cause the method area to overflow.

Solution

  • Adjust the method area size parameters (-XX:PermSize and -XX:MaxPermSize).
  • Optimize the loading and unloading mechanism of classes.

2.4 Constant pool overflow during runtime

reason

The constant pool stores data such as string constants during runtime, which will cause overflow when the constant pool is full and cannot be expanded.

Solution

  • Adjust the method area size parameters.
  • Avoid a large number of dynamically generated string constants.

2.5 Direct memory overflow from the machine

reason

Direct memory is used for direct memory operations, which will cause overflow when direct memory runs out.

Solution

  • Adjust the direct memory size parameter (-XX:MaxDirectMemorySize).
  • Optimize the code and release direct memory in time.

3. Summary

Java memory regions are divided into multiple parts, each region has its own specific uses and limitations. Understanding these memory areas and their corresponding memory overflow exceptions can help us better manage memory and optimize application performance. In actual development, we can prevent and solve memory overflow problems by reasonably configuring virtual machine parameters, optimizing code, etc. I hope this article can help you understand Java memory management and memory overflow exceptions in depth and improve your development skills.

This is the end of this article about the analysis and resolution of Java memory area and memory overflow exceptions. For more related Java memory area and memory overflow content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!