代碼如下:
private static Test [] test = null;public static void test(int count){if(count<10000000){count++;test = new Test[count];}System.out.println("count:"+count+" size:"+test.length);test(count);}public static void main(String... args){test(0);}
註:此文假設代碼沒有問題。 1:關於java棧的記憶體溢出 1.1:java.lang.StackOverflowError
此記憶體溢出說明,java棧的設定太小,我們可以藉助-Xss這個參數類比一下此異常,-Xss是用來設定棧的大小。右鍵 run as configurations,如下圖:
然後應用,然後run,我們發現控制台報錯,如下:
count:892 size:892count:893 size:893count:894 size:894Exception in thread "main" java.lang.StackOverflowErrorat sun.nio.cs.UTF_8.updatePositions(UTF_8.java:58)at sun.nio.cs.UTF_8$Encoder.encodeArrayLoop(UTF_8.java:392)at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:447)
我們可以看到到894次的時候,報錯了。我們可以更改-Xss的值,為-Xss100k然後再運行一次,輸入如下:
count:1925 size:1925count:1926 size:1926count:1927 size:1927count:1928 size:1928Exception in thread "main" java.lang.StackOverflowErrorat sun.nio.cs.UTF_8.updatePositions(UTF_8.java:58)at sun.nio.cs.UTF_8$Encoder.encodeArrayLoop(UTF_8.java:392)at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:447)
很明顯count的值增大了不少。 1.2:java.lang.OutOfMemoryError: unable to create new native thread
此異常說明,java棧的值設定的太大,以至於在建立線程,分配棧記憶體的時候發現系統記憶體小於設定的棧記憶體大小。我們可以按照上面的運行方式把-Xss的值設定成500m,如果你的電腦設定成500m後沒有報錯,那麼就繼續增大。我們看下控制台輸出,如下:
Error occurred during initialization of VMjava.lang.OutOfMemoryError: unable to create new native threadat java.lang.Thread.start0(Native Method)at java.lang.Thread.start(Thread.java:597)at java.lang.ref.Finalizer.<clinit>(Finalizer.java:176)
2:java堆的記憶體溢出 2.1:java.lang.OutOfMemoryError: Java heap space
此異常說明java堆設定的太小,我們可以用-Xms 和-Xmx來設定。具體就不再這裡說明了。