package cn.sp.test03;
import java.util.ArrayList;
import java.util.List;
/**
* JVM堆内存溢出
* @author 2YSP
*
*/
public class TestOOM {
static class OOMObject{
}
public static void main(String[] args) {
List<OOMObject> list=new ArrayList<OOMObject>();
while(true){
list.add(new OOMObject());
}
}
}
当程序不断的new一个对象,GC却来不及回收的时候,就会造成内存溢出。抛出如下异常。
java.lang.OutOfMemoryError: Java heap space
Dumping heap to java_pid8292.hprof ...
Heap dump file created [27869904 bytes in 0.155 secs]
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.util.Arrays.copyOf(Unknown Source)
at java.util.ArrayList.grow(Unknown Source)
at java.util.ArrayList.ensureExplicitCapacity(Unknown Source)
at java.util.ArrayList.ensureCapacityInternal(Unknown Source)
at java.util.ArrayList.add(Unknown Source)
at cn.sp.test03.TestOOM.main(TestOOM.java:18)
package cn.sp.test03;
/**
* 虚拟机栈溢出
* @author 2YSP
*
*/
public class TestOOM2 {
static int stackIndex = 0;
public void testStackOverFlow(){
stackIndex++;
/*int str = 12;
int str2 = 12;
int str3 = 12;
int str4 = 12;
int str5 = 12;
int str6 = 12;
int str7 = 12;
int str8 = 12;*/
testStackOverFlow();
}
public static void main(String[] args) throws Throwable {
try {
TestOOM2 oom=new TestOOM2();
oom.testStackOverFlow();
} catch (Throwable e) {
System.out.println("堆栈深度(迭代次数):"+stackIndex);
throw e;
}
}
}
一个方法无限调用自身的话,就会栈溢出,同时抛出以下异常。
堆栈深度(迭代次数):984
Exception in thread "main" java.lang.StackOverflowError
at cn.sp.test03.TestOOM2.testStackOverFlow(TestOOM2.java:11)
at cn.sp.test03.TestOOM2.testStackOverFlow(TestOOM2.java:21)
at cn.sp.test03.TestOOM2.testStackOverFlow(TestOOM2.java:21)
at cn.sp.test03.TestOOM2.testStackOverFlow(TestOOM2.java:21)
at cn.sp.test03.TestOOM2.testStackOverFlow(TestOOM2.java:21)
如果我们把注释部分去掉,再运行一次就会发现,栈深度更少了,这是因为变量也占用了内存。
堆栈深度(迭代次数):577
Exception in thread "main" java.lang.StackOverflowError
at cn.sp.test03.TestOOM2.testStackOverFlow(TestOOM2.java:11)
at cn.sp.test03.TestOOM2.testStackOverFlow(TestOOM2.java:21)
at cn.sp.test03.TestOOM2.testStackOverFlow(TestOOM2.java:21)
at cn.sp.test03.TestOOM2.testStackOverFlow(TestOOM2.java:21)
at cn.sp.test03.TestOOM2.testStackOverFlow(TestOOM2.java:21)
at cn.sp.test03.TestOOM2.testStackOverFlow(TestOOM2.java:21)