编写各种OutOfMemory & StackOverflow程序

自己编写各种outofmemory,stackoverflow程序

HeapOutOfMemory
Young OutOfMemory
MethodArea OutOfMemory
ConstantPool OutOfMemory
DirectMemory OutOfMemory
Stack OutOfMemory Stack OverFlow

这是网上某篇称为Java大牛中列出来的一条项目,下面进行简单的自己的实现:


1、HeapOutOfMemory

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

package com.test;

import java.util.ArrayList;

/**
 * Created by littlewolf on 11/1/2016.
 */
public class Demo {
    public static void main(String[] args) throws Exception {
        ArrayList<String> strs = new ArrayList<String>(100000000);
        for ( int i = 0; i <= 100000000; i++ ) {
            strs.add(Integer.toString(i));
            if( i % 10000 == 0 ) {
                System.out.println("i: " + i);
            }
        }
    }
}
电脑风扇已经开始狂转了~

2、Young OutOfMemory

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

3、MethodArea OutOfMemory

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

4、ConstantPool OutOfMemory

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

5、DirectMemory OutOfMemory

堆外溢出一般与NIO有关。

package com.test;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by littlewolf on 11/1/2016.
 */
public class Demo {
    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);
        }
    }
}


6、StackOverflow

栈溢出一般与方法递归次数过多,或者方法中有产生大量数据的循环有关。

package com.test;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by littlewolf on 11/1/2016.
 */
public class Demo {
    public static void main(String[] args) throws Exception {
        new Demo().mtd();
    }

    public void mtd() {
        long time = System.currentTimeMillis();
        mtd();
    }
}



参考:点击打开链接



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值