编写各种outofmemory/stackoverflow程序

来源:互联网 发布:淘宝网秋季女装 编辑:程序博客网 时间:2024/05/16 02:04
最近在网上看到一片文章Java工程师成神之路,对其中的
1.1.5. 自己编写各种outofmemory,stackoverflow程序HeapOutOfMemoryYoung OutOfMemoryMethodArea OutOfMemoryConstantPool OutOfMemoryDirectMemory OutOfMemoryStack OutOfMemory Stack OverFlow
这一栏的内容作了一些学习,在此记录,希望能为其他学习的同学带来一些提示。
共勉。

HeapOutOfMemory
堆溢出 情况多见于对象过多,存在多余引用,使对象未及时释放

public class Miao {    public static void main(String[] args) throws Exception{        ArrayList<String> strs = new ArrayList<>(10000_0000);        for(int i = 0 ;i <= 10000_0000; ++ i){            strs.add(Integer.toString(i));            if(i % 10000 == 0){                System.out.println(i);            }        }    }}

Young OutOfMemory
设置XX:MaxTenuringThreshold为一个很大的值
使对象无法及时的移动到年老代中,导致年轻代内存溢出

MethodArea OutOfMemory
在经常动态生成大量Class的应用中,需要特别注意类的回收状况。这类场景除了上面提到的程序使用了CGLib字节码增强和动态语言
之外,常见的还有:大量JSP或动态产生JSP文件的应用(JSP第一次运行时需要编译为Java类)、基于OSGi的应用(即使是同一个类文
件,被不同的加载器加载也会视为不同的类)等。

ConstantPool OutOfMemory
一般来说是不可能的,只有项目启动方法区内存很小或者项目中的静态变量极其多时才会发生

DirectMemory OutOfMemory
堆外内存溢出 一般与nio有关
public class Miao {    public static void main(String[] args) throws Exception{        List<ByteBuffer> buffers = new ArrayList<>();        while(true){            ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024 * 1024);            buffers.add(buffer);        }    }}



Stack OutOfMemory Stack OverFlow
栈溢出 一般与方法递归次数过多或者方法中有产生大量数据的循环有关
public class Miao {    public static void main(String[] args) throws Exception{        new Miao().miao();    }    public void miao(){        long time = System.currentTimeMillis();        miao();    }}



0 0