詳解JVM棧溢出和堆溢出

一、棧溢出StackOverflowError

棧是線程私有的,生命周期與線程相同,每個方法在執行的時候都會創建一個棧幀,用來存儲局部變量表,操作數棧,動態鏈接,方法出口等信息。

棧溢出:方法執行時創建的棧幀個數超過瞭棧的深度。

原因舉例:方法遞歸

【示例】:

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();
    }
}

【輸出】:

image-20210607200650249

解決方法:調整JVM棧的大小:-Xss

-Xss size

Sets the thread stack size (in bytes). Append the letter k or K to indicate KB, m or M to indicate MB, and g or G to indicate GB. The default value depends on the platform:

Linux/x64 (64-bit): 1024 KBmacOS (64-bit): 1024 KBOracle Solaris/x64 (64-bit): 1024 KBWindows: The default value depends on virtual memory

The following examples set the thread stack size to 1024 KB in different units:

-Xss1m
-Xss1024k
-Xss1048576

This option is similar to -XX:ThreadStackSize.

在IDEA中點擊Run菜單的Edit Configuration如下圖:

image-20210607204536807

設置後,再次運行,會發現i的值變小,這是因為設置的-Xss值比原來的小:

image-20210607204609661

二、堆溢出OutOfMemoryError:Java heap space

堆中主要存放的是對象。

堆溢出:不斷的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();
        }
    }
}

【輸出】:

image-20210607205142448

解決方法:調整堆的大小: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 or K to indicate kilobytes, m or M to indicate megabytes, and g or G 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
-Xmx80m

The -Xmx option is equivalent to -XX:MaxHeapSize.

設置-Xmx256M後,輸入如下,比之前小:

image-20210607210040480

到此這篇關於詳解JVM棧溢出和堆溢出的文章就介紹到這瞭,更多相關棧溢出和堆溢出內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: