Table of Contents
Java Heap OutOfMemoryError
Java stackStackOverflowError
Method area memory overflow
Runtime constant pool overflow
Memory overflow in the method area
MetaSpace memory overflow
Home Java javaTutorial Java common memory overflow exceptions and code implementation

Java common memory overflow exceptions and code implementation

Feb 23, 2017 am 10:38 AM
java

Java Heap OutOfMemoryError

The Java heap is used to store object instances, so if we continue to create objects and ensure that there is a reachable path between the GC Root and the created object to prevent the object from being garbage collected, Then when too many objects are created, it will cause insufficient memory in the heap, which will trigger an OutOfMemoryError exception.

/**
 * @author xiongyongshun
 * VM Args: java -Xms10m -Xmx10m -XX:+HeapDumpOnOutOfMemoryError
 */
public class OutOfMemoryErrorTest {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        int i = 0;
        while (true) {
            list.add(i++);
        }
    }
}
Copy after login

The above is a code that triggers an OutOfMemoryError exception. We can see that it continuously Create objects independently and save the objects in the list to prevent them from being garbage collected. Therefore, when there are too many objects, the heap memory will overflow.

Through java -Xms10m -Xmx10m -XX:+HeapDumpOnOutOfMemoryError we set the heap memory to 10 MB, and use the parameter -XX:+HeapDumpOnOutOfMemoryError to let the JVM print out the current memory snapshot when an OutOfMemoryError exception occurs for subsequent convenience Analysis.

After compiling and running the above code, there will be the following output:

>>> java -Xms10m -Xmx10m -XX:+HeapDumpOnOutOfMemoryError com.test.OutOfMemoryErrorTest                                                                                            16-10-02 23:35
java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid1810.hprof ...
Heap dump file created [14212861 bytes in 0.125 secs]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
        at java.util.Arrays.copyOf(Arrays.java:3210)
        at java.util.Arrays.copyOf(Arrays.java:3181)
        at java.util.ArrayList.grow(ArrayList.java:261)
        at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
        at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
        at java.util.ArrayList.add(ArrayList.java:458)
        at com.test.OutOfMemoryErrorTest.main(OutOfMemoryErrorTest.java:15)
Copy after login

Java stackStackOverflowError

We know that the runtime data area of ​​the JVM There is a memory area called the virtual machine stack. The role of this area is: each method will create a stack frame when executed, which is used to store local variable tables, operand stacks, method exits and other information.

So we can create an infinitely recursive recursive call. When the recursion depth is too large, the stack space will be exhausted, which will lead to a StackOverflowError exception.

The following is the specific code:

/**
 * @author xiongyongshun
 * VM Args: java -Xss64k
 */
public class OutOfMemoryErrorTest {
    public static void main(String[] args) {
        stackOutOfMemoryError(1);
    }
    public static void stackOutOfMemoryError(int depth) {
        depth++;
        stackOutOfMemoryError(depth);
    }
}
Copy after login

When the above code is compiled and run, the following exception message will be output:

Exception in thread "main" java.lang.StackOverflowError
    at com.test.OutOfMemoryErrorTest.stackOutOfMemoryError(OutOfMemoryErrorTest.java:27)
Copy after login

Method area memory overflow

, 因为 JDK8 已经移除了永久代, 取而代之的是 metaspace, 因此在 JDK8 中, 下面两个例子都不会导致 java.lang.OutOfMemoryError: PermGen space 异常.
Copy after login


Runtime constant pool overflow

In Java 1.6 and previous HotSpot JVM versions, there is the concept of the permanent generation, that is, the generational collection mechanism of GC is extended to the method area. In the method area , a part of the memory is used to store the constant pool, so if there are too many constants in the code, the constant pool memory will be exhausted, leading to memory overflow. So how to add a large number of constants to the constant pool? At this time, you need to rely on String. intern() method. The function of String.intern() method is: if the value of this String already exists in the constant pool, this method returns the reference of the corresponding string in the constant pool; otherwise, the value contained in this String is added. to the constant pool, and returns a reference to this String object. In JDK 1.6 and previous versions, the constant pool is allocated in the permanent generation, so we can set the parameters "-XX:PermSize" and "-XX:MaxPermSize" to Indirectly limit the size of the constant pool.

, 上面所说的 String.intern() 方法和常量池的内存分布仅仅针对于 JDK 1.6 及之前的版本, 在 JDK 1.7 或以上的版本中, 由于去除了永久代的概念, 因此内存布局稍有不同.
Copy after login


The following is a code example to implement constant pool memory overflow:

/**
 * @author xiongyongshun
 * VM Args:  -XX:PermSize=10M -XX:MaxPermSize=10M 
 */
public class RuntimeConstantPoolOOMTest {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        int i = 0;
        while (true) {
            list.add(String.valueOf(i++).intern());
        }
    }
}
Copy after login

We see , in this example, the String.intern() method is used to add a large number of string constants to the constant pool, thus causing the memory overflow of the constant pool.

We compile and compile through JDK1.6 Running the above code, there will be the following output:

Exception in thread "main" java.lang.OutOfMemoryError: PermGen space
        at java.lang.String.intern(Native Method)
        at com.test.RuntimeConstantPoolOOMTest.main(RuntimeConstantPoolOOMTest.java:16)
Copy after login
, 如果通过 JDK1.8 来编译运行上面代码的话, 会有如下警告, 并且不会产生任何的异常:
Copy after login
>>> java -XX:PermSize=10M -XX:MaxPermSize=10M com.test.RuntimeConstantPoolOOMTest                                                                                                  16-10-03 0:23
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option PermSize=10M; support was removed in 8.0
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=10M; support was removed in 8.0
Copy after login

Memory overflow in the method area

The method area is used to store Class-related information, such as class name, class access Modifiers, field descriptions, method descriptions, etc. Therefore, if the method area is too small and too many classes are loaded, the memory in the method area will overflow.

//VM Args:  -XX:PermSize=10M -XX:MaxPermSize=10M
public class MethodAreaOOMTest {
    public static void main(String[] args) {
        while (true) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(MethodAreaOOMTest.class);
            enhancer.setUseCache(false);
            enhancer.setCallback(new MethodInterceptor() {
                public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                    return methodProxy.invokeSuper(o, objects);
                }
            });
            enhancer.create();
        }
    }
}
Copy after login

In the above code , we use CGlib to dynamically generate a large number of classes. Under JDK6, running the above code will generate an OutOfMemoryError: PermGen space exception:

/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Home /bin/java -jar -XX:PermSize=10M -XX:MaxPermSize=10M target/Test-1.0-SNAPSHOT.jar
The output results are as follows:

Caused by: java.lang.OutOfMemoryError: PermGen space
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(ClassLoader.java:637)
        at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
        ... 11 more
Copy after login

MetaSpace memory overflow

In the section Memory Overflow in the Method Area, we mentioned that JDK8 does not have the concept of permanent generation, so the two examples did not achieve the expected results under JDK8. So under JDK8, whether Are there errors like memory overflow in the method area? Of course there are. In JDK8, the MetaSpace area is used to store Class-related information, so when the MetaSpace memory space is insufficient, java.lang.OutOfMemoryError: Metaspace will be thrown Exception.

We still take the example mentioned above as an example:

//VM Args: -XX:MaxMetaspaceSize=10M
public class MethodAreaOOMTest {
    public static void main(String[] args) {
        while (true) {
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(MethodAreaOOMTest.class);
            enhancer.setUseCache(false);
            enhancer.setCallback(new MethodInterceptor() {
                public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                    return methodProxy.invokeSuper(o, objects);
                }
            });
            enhancer.create();
        }
    }
}
Copy after login

The code part of this example has not been changed, the only difference is that we need to use JDK8 to run This code is set with the parameter -XX:MaxMetaspaceSize=10M. This parameter tells the JVM that the maximum size of Metaspace is 10M.

Then we use JDK8 to compile and run this example, and the following exception is output:

>>> java -jar -XX:MaxMetaspaceSize=10M target/Test-1.0-SNAPSHOT.jar
Exception in thread "main" java.lang.OutOfMemoryError: Metaspace
    at net.sf.cglib.core.AbstractClassGenerator.generate(AbstractClassGenerator.java:345)
    at net.sf.cglib.proxy.Enhancer.generate(Enhancer.java:492)
    at net.sf.cglib.core.AbstractClassGenerator$ClassLoaderData.get(AbstractClassGenerator.java:114)
    at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:291)
    at net.sf.cglib.proxy.Enhancer.createHelper(Enhancer.java:480)
    at net.sf.cglib.proxy.Enhancer.create(Enhancer.java:305)
    at com.test.MethodAreaOOMTest.main(MethodAreaOOMTest.java:22)
Copy after login

The above is the content of common Java memory overflow exceptions and code implementation. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!




Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles