Integer类中的缓存Cache

来源:互联网 发布:ichart.js 编辑:程序博客网 时间:2024/05/14 10:02

Integer 类将 [-128-127] 这256个数字实例化了,也就是说用 Integer 来实例化其中某个数都是直接调用缓存中的实例,创建的多个实例都是同一个。 


下面这个Demo 能够很好的说明这个问题:

public class Test {    public static void main(String[] args) {        Integer int1 = Integer.valueOf("100");        Integer int2 = Integer.valueOf("100");        System.out.println(int1 == int2); //  return true    }}

我们看一下JDK 中Integer 类的源码:


public static Integer valueOf(String s) throws NumberFormatException {        return Integer.valueOf(parseInt(s, 10));    }public static Integer valueOf(int i) {        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)];        return new Integer(i);    }

在解析时调用了IntegerCache这个类,这个类时Integer的一个内部静态类,用来缓存 [-128-127]  这些数字。

 /**     * Cache to support the object identity semantics of autoboxing for values between     * -128 and 127 (inclusive) as required by JLS.     *     * The cache is initialized on first usage.  The size of the cache     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.     * During VM initialization, java.lang.Integer.IntegerCache.high property     * may be set and saved in the private system properties in the     * sun.misc.VM class.     */    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 对缓存数字的 high 值的上限做了一个调整,允许我们自行设置范围的上限。


对于Long类、Short类,JDK同样做了缓存操作,区别在于他们不能调整 high值。


private static class LongCache {        private LongCache(){}        static final Long cache[] = new Long[-(-128) + 127 + 1];        static {            for(int i = 0; i < cache.length; i++)                cache[i] = new Long(i - 128);        }    }



原创粉丝点击