溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用JVM怎么實現棧溢出和堆溢出

發布時間:2021-06-09 16:31:09 來源:億速云 閱讀:439 作者:Leah 欄目:開發技術

本篇文章為大家展示了使用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();
    }
}

【輸出】:

使用JVM怎么實現棧溢出和堆溢出

解決方法:調整JVM棧的大?。?code>-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如下圖:

使用JVM怎么實現棧溢出和堆溢出

設置后,再次運行,會發現i的值變小,這是因為設置的-Xss值比原來的?。?/p>

使用JVM怎么實現棧溢出和堆溢出

二、堆溢出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();
        }
    }
}

【輸出】:

使用JVM怎么實現棧溢出和堆溢出

解決方法:調整堆的大?。?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 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后,輸入如下,比之前?。?/p>

使用JVM怎么實現棧溢出和堆溢出

上述內容就是使用JVM怎么實現棧溢出和堆溢出,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

jvm
AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女