本篇文章為大家展示了使用JVM怎么實現棧溢出和堆溢出,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
棧是線程私有的,生命周期與線程相同,每個方法在執行的時候都會創建一個棧幀,用來存儲局部變量表,操作數棧,動態鏈接,方法出口等信息。
棧溢出:方法執行時創建的棧幀個數超過了棧的深度。
原因舉例:方法遞歸
【示例】:
public class StackError { private int i = 0; public void fn() { System.out.println(i++); fn(); } public static void main(String[] args) { StackError stackError = new StackError(); stackError.fn(); } }
【輸出】:
解決方法:調整JVM棧的大?。?code>-Xss
-Xss size
Sets the thread stack size (in bytes). Append the letter
Linux/x64 (64-bit): 1024 KBmacOS (64-bit): 1024 KBOracle Solaris/x64 (64-bit): 1024 KBWindows: The default value depends on virtual memoryk
orK
to indicate KB,m
orM
to indicate MB, andg
orG
to indicate GB. The default value depends on the platform:The following examples set the thread stack size to 1024 KB in different units:
-Xss1m
-Xss1024k
-Xss1048576This option is similar to
-XX:ThreadStackSize
.
在IDEA中點擊Run菜單的Edit Configuration如下圖:
設置后,再次運行,會發現i的值變小,這是因為設置的-Xss值比原來的?。?/p>
堆中主要存放的是對象。
堆溢出:不斷的new
對象會導致堆中空間溢出。如果虛擬機的棧內存允許動態擴展,當擴展棧容量無法申請到足夠的內存時。
【示例】:
public class HeapError { public static void main(String[] args) { List<String> list = new ArrayList<>(); try { while (true) { list.add("Floweryu"); } } catch (Throwable e) { System.out.println(list.size()); e.printStackTrace(); } } }
【輸出】:
解決方法:調整堆的大?。?code>Xmx
-Xmx size
Specifies the maximum size (in bytes) of the memory allocation pool in bytes. This value must be a multiple of 1024 and greater than 2 MB. Append the letter
k
orK
to indicate kilobytes,m
orM
to indicate megabytes, andg
orG
to indicate gigabytes. The default value is chosen at runtime based on system configuration. For server deployments,-Xms
and-Xmx
are often set to the same value. The following examples show how to set the maximum allowed size of allocated memory to 80 MB by using various units:-Xmx83886080
-Xmx81920k
-Xmx80mThe
-Xmx
option is equivalent to-XX:MaxHeapSize
.
設置-Xmx256M
后,輸入如下,比之前?。?/p>
上述內容就是使用JVM怎么實現棧溢出和堆溢出,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。