程序小寨

Java基础-数据类型缓存解析

2018-12-19  本文已影响7人  梦中一点心雨

基本类型缓存解析

Integer缓存解析:

    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) {
                int i = parseInt(integerCacheHighPropValue);
                i = Math.max(i, 127);
                // Maximum array size is Integer.MAX_VALUE
                h = Math.min(i, Integer.MAX_VALUE - (-low));
            }
            high = h;
            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);
        }
        private IntegerCache() {}
    }

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

1、使用自动装箱(Integer i = 1)方式创建Integer对象时,会使用valueOf进行Integer对象的初始化,此时,会调用IntegerCache.high,这是需要对IntegerCache这个静态内部类进行初始化。<p>
2、IntegerCache类中有一个cache数组,在加载IntegerCache的时候,会将-128到127的Integer对象都创建了,并存到cache数组中,然后在判断当前初始化的Integer对象的值是否在-128到127之间,如果是,就直接从cache缓存中取,如果不存在,则new一个新的Integer对象。<p>
3、之后再使用自动装箱的方式创建Integer对象时,值在-128到127之间时会直接从cache缓存中取。<p>

所以,使用自动装箱的方式创建的Integer对象,两者进行比较时,只要其值相等就是ture。而不在-128到127之间的,比较时会新new一个对象,而导致比较结果为false<p>
****注意****:Integer的最低值是固定的,只能是-128,而最高值是可以通过jvm参数设置的。在执行java程序的时候加上-XX:AutoBoxCacheMax=<size>参数即可。

Long及Byte、Character缓存解析

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

    public static Long valueOf(long l) {
        final int offset = 128;
        if (l >= -128 && l <= 127) { // will cache
            return LongCache.cache[(int)l + offset];
        }
        return new Long(l);
    }

Long的缓存机制(LongCache)与Integer的类似,还有Character(CharacterCache),Byte(ByteCache)的缓存机制也是类似。不过只有Integer的最大值可以通过jvm参数设置,其他的都固定的。其中,Byte,Short,Long 的范围: -128 到 127;Character, 范围是 0 到 127。

上一篇 下一篇

猜你喜欢

热点阅读