OutOfMemoryError和StackOverflowError异常demo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huuuuuuuu/article/details/72770357
/**
 * java堆溢出
 * 虚拟机参数: -Xms:30m -Xmx30m -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());
        }
    }
}
/**
 * 虚拟机栈和本地方发栈溢出
 * -Xss128k
 */
public class JavaVMStackSOF {
    private int stackLength =1;
    public void stackLeak(){
        stackLength++;
        stackLeak();
    }
    public static void main(String[] args) throws Throwable{
        JavaVMStackSOF oom = new JavaVMStackSOF();
        try{
            oom.stackLeak();
        }catch (Throwable e){
            System.out.println("stack length:"+ oom.stackLength);
            throw e;
        }
    }
}
/**
 * 虚拟机栈和本地方发栈溢出
 * -Xss128k
 */
public class JavaVMStackSOF {
    private int stackLength =1;
    public void stackLeak(){
        stackLength++;
        stackLeak();
    }
    public static void main(String[] args) throws Throwable{
        JavaVMStackSOF oom = new JavaVMStackSOF();
        try{
            oom.stackLeak();
        }catch (Throwable e){
            System.out.println("stack length:"+ oom.stackLength);
            throw e;
        }
    }
}
/**
 * jdk6及之前版本常量池分配在永生代中,通过
 * -XX:PermSize=10M -XX:MaxPermSize=10M限制常量池
 * jdk7开始去永生代,所以这里会一直循环下去
 * Created by hyh on 2017/5/26.
 */
public class RuntimeConstantPoolOOM {
    public static void main(String[] args){
        //使用list保持常量池的引用,避免Full FC回收常量池的行为
        List<String> list=new ArrayList<String>();
        int i=0;
        while (true){
            //String.intern()为Native方法:常量池中已有此String对象的字符串就直接返回对象,否则添加到其中并返回对象的引用
            list.add(String.valueOf(i++).intern());
        }
    }
}

/**
 * 直接内存溢出
 * -Xmx20M -XX:MaxDirectMemorySize=10M
 * Created by hyh on 2017/5/26.
 */
public class DirectMemoryOOM {
    private static final int size=1024*1024;
    public static void main (String[] args) throws IllegalAccessException {
        Field field= Unsafe.class.getDeclaredFields()[0];
        field.setAccessible(true);
        Unsafe unsafe= (Unsafe) field.get(null);
        while(true){
            unsafe.allocateMemory(size);
        }
    }
}



猜你喜欢

转载自blog.csdn.net/huuuuuuuu/article/details/72770357