使用JVM怎么实现栈溢出和堆溢出

发布时间:2021-06-09 16:31:09 作者:Leah
来源:亿速云 阅读:381

本篇文章为大家展示了使用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怎么实现栈溢出和堆溢出

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

-Xss size

Sets the thread stack size (in bytes). Append the letter k or K to indicate KB, m or M to indicate MB, and g or G to 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如下图:

使用JVM怎么实现栈溢出和堆溢出

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

使用JVM怎么实现栈溢出和堆溢出

二、堆溢出OutOfMemoryError:Java heap space

堆中主要存放的是对象。

堆溢出:不断的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();
        }
    }
}

【输出】:

使用JVM怎么实现栈溢出和堆溢出

解决方法:调整堆的大小: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后,输入如下,比之前小:

使用JVM怎么实现栈溢出和堆溢出

上述内容就是使用JVM怎么实现栈溢出和堆溢出,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. 使用maven编译scala项目时栈溢出
  2. Microsoft SQL Server 堆栈溢出漏洞加固

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

jvm

上一篇:怎么在Java中使用字节流实现图片音频的复制

下一篇:怎么在Html5中实现应用程序缓存

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》