JVM(2)--OutOfMemoryError实战

一、堆溢出

点击它选择Run Configurations,进入

左边选择Java Application,选择要操作的例子,右边选择Arguments,

 在VM arguments里面设置-Xms20M -Xmx20M -XX:+HeapDumpOnOutOfMemoryError

使堆的最大最小内存为20M,并且dump出当前的内存堆转储快照

要使堆溢出,只要不断创建对象,而且使GCRoots对对象可达,使对象不被清理就行。

demo的代码如下

    static class test{}
    public static void main(String[] args) {
        ArrayList<test> al=new ArrayList<test>();
        while(true)
        {
            al.add(new test());
        }
    }

接下来就可以在控制台看到:

二、虚拟机栈和本地方法栈溢出

Hotspot中虚拟机栈和本地方法栈是一起的,这次我们设置VM -Xss20M,虚拟机栈设为20M

然后代码如下:

    static public void test()
    {
        test();
    }
    public static void main(String[] args) {
        test();
    }

不过这是抛出的是,Exception in thread "main" java.lang.StackOverflowError

不写递归,改写创建线程:

public static void main(String[] args) {
        while(true)
        {
            Thread t=new Thread(){
                public void run()
                {
                    while(true)
                    {
                    }
                }
            };
            t.start();
        }
    }

结果是

三、方法区和运行时常量池溢出

因为是jdk1.6所以可以通过-XX:PermSize=10M -XX:MaxPermSize=10M设置方法区大小,运行时常量池在方法区中,所以也被间接的限制。

String.intern(),作用是如果字符串常量池存在则返回对象,不存在则添加到常量池再返回。

代码如下:

public static void main(String[] args) {
        ArrayList<String> al=new ArrayList<String>();
        int i=0;
        while(true)
        {
            al.add(String.valueOf(++i).intern());
        }
    }

结果如下:

原文地址:https://www.cnblogs.com/blogofjzq/p/9390736.html