JVM内存溢出情况

9/6/2015来源:Java教程人气:1608

JVM内存溢出情况

《深入理解java虚拟机》一书中介绍到jvm的内存溢出情况,对理解jvm的自动内存管理机制有一定帮助,下面通过几个实例来进行说明。

java虚拟机的规范描述中,除了程序计数器外,java堆,虚拟机栈,本地方法区等运行时区都会发生outOfMemoryError的可能。

《1》java堆溢出

//eclipse-run configurations-VM arguments-Xms20M -Xmx20M -Xmn10M -XX:+HeapDumpOnOutOfMemoryError

public class HeapOOM{    static class OOMObject    {            }    public static void main(String[] args)    {        List<OOMObject> list=new ArrayList<OOMObject>();        while(true)        {            list.add(new OOMObject());        }    }}
View Code

《2》虚拟机栈和本地方法栈溢出

//-Xss128k

代码一产生的是stackoverflowerror,

public class JVMStacks{    PRivate int stackLength=1;    public void stackLeak()    {        stackLength++;        stackLeak();    }    public static void main(String[] args)    {        JVMStacks  oom=new JVMStacks();        try        {            oom.stackLeak();        }catch(Throwable e)        {            System.out.println(oom.stackLength);            throw new RuntimeException(e);        }    }}
View Code

//-Xss2M

通过代码二可以产生内存溢出异常,但是往往会使你的计算机进入假死状态

public void JAVAStack{   private void dostop(){    while(true){};}public void stackLeak(){   while(true){  Thread thread =new Thread(new Runnable(){  public void run(){dostop();}});thread.start();}}public void main(String[] args){JAVAStack  oom=new  JavaStack();oom.stackLeak();}}
View Code

《3》运行时常量池内存溢出

//-XX:PermSize=10M -XX:MaxPermSize=10M

public class RuntimeConstantPool{    /**     * @param args     */    public static void main(String[] args)    {        List<String> list=new ArrayList<String>();        int i=0;        while(true)        {            list.add(String.valueOf(i++).intern());        }    }}
View Code

《4》本机直接内存溢出

/** * VM Args:-Xmx20M -XX:MaxDirectMemorySize=10M * @author zzm */public class DirectMemoryOOM {    private static final int _1MB = 1024 * 1024;    public static void main(String[] args) throws Exception {        Field unsafeField = Unsafe.class.getDeclaredFields()[0];        unsafeField.setaccessible(true);        Unsafe unsafe = (Unsafe) unsafeField.get(null);        while (true) {            unsafe.allocateMemory(_1MB);        }    }}
View Code