欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

理解栈溢出与堆溢出之二:Java堆内存空间不足引发的OutOfMemoryError

最编程 2024-02-12 13:07:15
...

堆中主要存放的是对象。

堆溢出:不断的new对象会导致堆中空间溢出。如果虚拟机的栈内存允许动态扩展,当扩展栈容量无法申请到足够的内存时。

【示例】:

public class HeapError {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        try {
            while (true) {
                list.add("Floweryu");
            }
        } catch (Throwable e) {
            System.out.println(list.size());
            e.printStackTrace();
        }
    }
}

【输出】:

image-20210607205142448

解决方法:调整堆的大小:Xmx

-Xmx size

Specifies the maximum size (in bytes) of the memory allocation pool in bytes. This value must be a multiple of 1024 and greater than 2 MB. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, and g or G to indicate gigabytes. The default value is chosen at runtime based on system configuration. For server deployments, -Xms and -Xmx are often set to the same value. The following examples show how to set the maximum allowed size of allocated memory to 80 MB by using various units:

-Xmx83886080
-Xmx81920k
-Xmx80m

The -Xmx option is equivalent to -XX:MaxHeapSize.

设置-Xmx256M后,输入如下,比之前小:
image-20210607210040480