1.我们知道对象创建时,给对象开辟的内存在Heap上,如果对象足够多,或者对象足够大,导致Heap的内存不够分配时就会导致堆溢出。
2.我们知道值类型的变量存储在栈空间,如果值类型变量足够多也会导致栈溢出,同时我们还知道函数的递归调用也会进行压栈操作。
3.下面我们写个小程序来测试一下如果使用堆和栈溢出。
package com.dangdang
import java.util.ArrayList;
import java.util.List;
public class MemoryLeak {
public static void main(String[] args) throws Exception {
char input;
System.out.println("Input 1 to test Heap_Memory_Leak, others to test Stack_Memory_Lead");
input = (char)System.in.read();
if ('1' == input) {
System.out.println("Began to test Heap memory leak!");
new MemoryLeak().new MyMemory().HeapLeakTest();
}
else{
new MemoryLeak().new MyMemory().StackLeakTest();
}
}
class MyMemory{
public MyMemory(){
}
// the objects is stored in Heap
public void HeapLeakTest(){
List<int[]> intlist = new ArrayList<int[]>();
while(true){
int[] leakint = new int[10000000];
intlist.add(leakint);
}
}
// recursion will do push stack action
public void StackLeakTest(){
StackLeakTest();
}
}
}
4. 测试结果
堆溢出
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at com.dangdang.MemoryLeak$MyMemory.HeapLeakTest(MemoryLeak.java:27)
at com.dangdang.MemoryLeak.main(MemoryLeak.java:12)
栈溢出
Exception in thread "main" java.lang.StackOverflowError
at com.dangdang.MemoryLeak$MyMemory.StackLeakTest(MemoryLeak.java:34)
at com.dangdang.MemoryLeak$MyMemory.StackLeakTest(MemoryLeak.java:34)
.....
-------迁移自个人空间------