Java Memory Leak Test



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)

    .....


-------遷移自個人空間------

發佈了40 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章