自己编写各种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();
}
}
参考:点击打开链接