Java中的常量類緩存機制

還記得被多個對象的判斷==/equals支配的恐懼嗎?java

隨便來一個,shell

public static void main(String[] args) {
        Integer i  = 12; //1
        Integer i1  = 12; //2

        Integer i2  = 129; //3
        Integer i3  = 129; //4

        System.out.println(i == i1); // 5
        System.out.println(i2 == i3); //6

    }
複製代碼

這個的輸出結果是什麼呢?數組

直接展現答案吧,輸出結果是:緩存

true
false
複製代碼

咱們來研究一下爲何.bash

首先咱們要知道,在1.5以後的JDK爲咱們提供了自動裝箱與拆箱,用來解決8中基本類型->對象的轉換問題,這一點若是不是很清楚了話能夠先google瞭解一下.學習

上面代碼中的語句1-4無疑都是發生了裝箱的,那麼咱們反編譯一下這段代碼,來看一下在裝箱過程當中到底發生了什麼.google

在命令行中執行如下命令:spa

javac IntegerTest.java
javap -v -c -s -l IntegerTest 
複製代碼

能夠看到輸出結果以下:命令行

2019-05-12-23-51-36

能夠看到自動裝箱的時候調用的是Integer.valueOf()方法,那麼咱們看一下他的實現:code

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
複製代碼

當傳入的數字在某個範圍(這個範圍默認是-128到127)之間時,直接返回緩存的一個列表,找一下緩存列表的初始化的地方:

private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

複製代碼

這是IntegerCache緩存類的實現,在類加載的時候用靜態方法快進行了初始化,將緩存範圍內的值預先加載好放在數組中.

能夠看到對緩存範圍的上限數字是經過讀取配置來設置的,所以,Integer的緩存範圍是能夠經過參數-XX:AutoBoxCacheMax=size來設置的.

其餘常量類的緩存

這種緩存行爲不只適用於Integer對象。針對全部整數類型的類都有相似的緩存機制。

  1. ByteCache 用於緩存 Byte 對象, 固定範圍[-128-127].

  2. ShortCache 用於緩存 Short 對象,固定範圍[-128-127].

  3. LongCache 用於緩存 Long 對象,固定範圍[-128-127].

  4. CharacterCache 用於緩存 Character 對象, 固定範圍[0-127].

而經過參數設置緩存範圍,只有Integer能夠.其餘的都不容許.





ChangeLog

2019-05-10 完成

以上皆爲我的所思所得,若有錯誤歡迎評論區指正。

歡迎轉載,煩請署名並保留原文連接。

聯繫郵箱:huyanshi2580@gmail.com

更多學習筆記見我的博客------>呼延十

相關文章
相關標籤/搜索