JVM栈溢出和堆溢出代码示例

作者:袖梨 2022-06-29

本篇文章小编给大家分享一下JVM栈溢出和堆溢出代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

一、栈溢出StackOverflowError

栈是线程私有的,生命周期与线程相同,每个方法在执行的时候都会创建一个栈帧,用来存储局部变量表,操作数栈,动态链接,方法出口等信息。

栈溢出:方法执行时创建的栈帧个数超过了栈的深度。

原因举例:方法递归

【示例】:

public class StackError {
    private int i = 0;

    public void fn() {
        System.out.println(i++);
        fn();
    }

    public static void main(String[] args) {
        StackError stackError = new StackError();
        stackError.fn();
    }
}

【输出】:

解决方法:调整JVM栈的大小:-Xss

-Xsssize

Sets the thread stack size (in bytes). Append the letterkorKto indicate KB,morMto indicate MB, andgorGto indicate GB. The default value depends on the platform:

Linux/x64 (64-bit): 1024 KBmacOS (64-bit): 1024 KBOracle Solaris/x64 (64-bit): 1024 KBWindows: The default value depends on virtual memory

The following examples set the thread stack size to 1024 KB in different units:

-Xss1m

-Xss1024k

-Xss1048576

This option is similar to-XX:ThreadStackSize.

在IDEA中点击Run菜单的Edit Configuration如下图:

设置后,再次运行,会发现i的值变小,这是因为设置的-Xss值比原来的小:

二、堆溢出OutOfMemoryError:Java heap space

堆中主要存放的是对象。

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

【示例】:

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

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

【输出】:

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

-Xmxsize

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 letterkorKto indicate kilobytes,morMto indicate megabytes, andgorGto indicate gigabytes. The default value is chosen at runtime based on system configuration. For server deployments,-Xmsand-Xmxare 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-Xmxoption is equivalent to-XX:MaxHeapSize.

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

相关文章

精彩推荐