JavaSE源码分析(一):基本类型包装类缓存机制

本文深入解析了Java中Integer、Byte、Short、Long和Character等包装类的缓存机制,通过源码分析揭示了在-128至127之间的整型值会使用缓存,避免了重复对象的创建。此外,文章还探讨了如何通过配置改变Integer的缓存范围,并总结了各包装类的缓存特点。通过对缓存机制的理解,有助于优化Java程序的性能。
摘要由CSDN通过智能技术生成

目录

前言

概述

Integer的缓存机制及原理

Byte包装类

Short包装类

Long包装类

Character包装类

总结

思考


前言

先看一道面试题,我们将通过这个面试题来引入本文的话题。

面试题:下面的代码运行结果是什么?

public class Test {

    public static void main(String[] args) {
        Integer f1 = 100, f2 = 100, f3 = 150, f4 = 150;

        System.out.println(f1 == f2);
        System.out.println(f3 == f4);
    }
}

答案:true  false。

如果你还不知道其中的原理,那么读完本文你应该就能得到你想要的。当然,如果你已经知道了原理,那么也欢迎你读完本文后,对不足之处加以斧正~

概述

要想正确回答这道看似简单的面试题,就必须对Java基本类型的包装类的缓存机制有一定的了解。我们知道,在Java是一个近乎纯粹的面向对象编程语言,但是为了编程的方便,Java中还是引入了8种基本数据类型,而为了对这些基本数据类型像对象一样操作,Java为每一个基本数据类型都提供了一个包装类(wrapper class)。而从JDK5开始,Java还引入了自动拆箱/装箱机制,更方便了基本数据类型和包装类型的转化。

基本数据类型:byte、short、int、long、float、double、char、boolean

包装类型:Byte、Short、Integer、Long、Float、Double、Character、Boolean

而在这些包装类中,Byte、Short、Integer、Long以及Character都有缓存机制,我们将主要以Integer为例对包装类型的缓存机制进行说明,并附上源码便于理解其原理。

Integer的缓存机制及原理

我们还是从文章开头的面试题入手,题中f1、f2、f3、f4都是Integer对象引用,所以==比较的就是它们的引用。答案很明显,就在给它们赋值时,发生的自动装箱上。那么是怎么自动装箱的呢?自动装箱的本质是通过Integer类的静态valueOf()方法来实现int到Integer的转换。

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

通过源码,我们已经可以发现端倪。当int值在IntegerCache.low和IntegerCache.high之间时,返回了IntegerCache.cache这个数组中的值,而当不在这个区间时,才会通过Integer的构造方法来新建一个Integer对象。

IntegerCache.low、IntegerCache.high以及IntegerCache.cache这三者明显都是指向了IntegerCache类。按图索骥,我们再看下IntegerCache这个类的源码。

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

这个类是Integer类的内部类,它的三个属性中:

(1)low:是固定值-128

(2)high:默认值为127,可以通过配置的java.lang.Integer.IntegerCache.high值来改变

(3)cache:是一个Integer数组,其中包括了(high-low+1)个Integer对象。按值从小到大排列,其中值的默认区间为[-128,127],最大值可通过high值的改变而改变

看到这里就能明白,面试题中,f1和f2的赋值是100,在区间[-128,127]内,因此自动装箱时,直接从缓存的数组中取出了缓存的Integer对象,由于引用的是同一个对象,所以f1==f2的结果是true。而f3和f4的赋值是150,不在缓存区间内,因此自动装箱时,各自新建了个Integer对象,所以f3==f4的结果是false。

需要注意的是:

1、配置的high值是有范围限制的。high值需要不得小于127,也不得大于Integer.MAX_VALUE-129,这是为了保证缓存的cache数组的大小不得小于256,也不得大于Integer.MAX_VALUE。换句话说,缓存的值至少是[-128,127],可以向正方向扩展,但总的缓存的值的个数不能超过int类型最大值,即2^31-1个。

2、只有Integer可以通过配置改变缓存的范围,其他的包装类都不行。

Byte包装类

理解了Integer类的缓存机制原理,其他包装类的原理都基本相同,所以这里就将源码附上,供大家参考比较。

    private static class ByteCache {
        private ByteCache(){}

        static final Byte cache[] = new Byte[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Byte((byte)(i - 128));
        }
    }

    public static Byte valueOf(byte b) {
        final int offset = 128;
        return ByteCache.cache[(int)b + offset];
    }

Short包装类

    private static class ShortCache {
        private ShortCache(){}

        static final Short cache[] = new Short[-(-128) + 127 + 1];

        static {
            for(int i = 0; i < cache.length; i++)
                cache[i] = new Short((short)(i - 128));
        }
    }    

    public static Short valueOf(short s) {
        final int offset = 128;
        int sAsInt = s;
        if (sAsInt >= -128 && sAsInt <= 127) { // must cache
            return ShortCache.cache[sAsInt + offset];
        }
        return new Short(s);
    }

Long包装类

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

Character包装类

    private static class CharacterCache {
        private CharacterCache(){}

        static final Character cache[] = new Character[127 + 1];

        static {
            for (int i = 0; i < cache.length; i++)
                cache[i] = new Character((char)i);
        }
    }

    public static Character valueOf(char c) {
        if (c <= 127) { // must cache
            return CharacterCache.cache[(int)c];
        }
        return new Character(c);
    }

总结

整型的缓存池范围默认都是: -128 到 127,字符型的缓存池范围是[0,127]区间内整数对应的字符。如果整型字面量的值在-128到127之间,那么不会new新的包装类对象,而是直接引用缓存池中的包装类对象,所以上面的面试题中f1==f2的结果是true,而f3==f4的结果是false。

思考

源码中可以通过配置IntegerCache的high值来扩大缓存的区间,为什么源码不通过配置low的值来扩大缓存区间呢?

笔者的浅见是相对来说,一般情况下使用默认的缓存区间已经足够,而且使用正值缓存的几率更大一些,没有必要去扩大负值缓存。若各位读友有更好的见解,可以通过评论交流,不胜感激~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值