分析java記憶體溢出

來源:互聯網
上載者:User

代碼如下:

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來設定。具體就不再這裡說明了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.