java人为制造溢出

来源:互联网 发布:家用投影仪知乎 编辑:程序博客网 时间:2024/05/02 04:20
  1. 堆内存溢出
package com.jvm.basics;import java.util.ArrayList;import java.util.List;public class HelloHeapOutOfMemeory{    public static void main(String[] args)    {        System.out.println("HelloHeapOutOfMemory");        List<Person> persons=new ArrayList<Person>();        int counter=0;        while(true)        {            persons.add(new Person());            System.out.println("Instance: "+(++counter));        }    }}class Person{}

运行参数

-verbose:gc -Xms10M -Xmx10M -XX:MaxDirectMemorySize=5M-Xss128k -XX:+PrintGCDetails
  1. 栈溢出
package com.jvm.basics;public class HelloStackOverFlow{    private int counter;    public void count()    {        counter++;        count();    }    public static void main(String[] args)    {        System.out.println("HelloStackOverFlow");        HelloStackOverFlow helloStackOverFlow=new HelloStackOverFlow();        try        {            helloStackOverFlow.count();         }        catch (Exception e)        {            e.printStackTrace();            throw e;        }    }}

3.常量溢出

package com.jvm.basics;import java.util.ArrayList;import java.util.List;public class HelloConstantOutOfMemeory{    public static void main(String[] args)    {        try        {            List<String> strList=new ArrayList<String>();            int item=0;            while(true)            {                strList.add(String.valueOf(item++).intern());            }        }        catch (Exception e)        {            e.printStackTrace();            throw e;        }    }}

这里写图片描述

  1. Direct buffer memory
package com.jvm.basics;import java.nio.ByteBuffer;import java.util.ArrayList;import java.util.List;public class HelloDirectMemoryOutOfMemory{    private static final int ONE_GB=1024*1024*1024;    private static int count=1;    public static void main(String[] args)    {        try        {            while(true)            {                ByteBuffer buffer=ByteBuffer.allocateDirect(ONE_GB);                count++;            }        }        catch (Exception e)        {            System.out.println("Exception: Instance Created "+count);            e.printStackTrace();        }        catch (Error e)        {            System.out.println("Error: Instance Created "+count);            e.printStackTrace();        }    }}

这里写图片描述