Java基础:128陷阱之Integer缓存源码研究
  TEZNKK3IfmPf 2024年04月12日 40 0

Java中Integer的缓存实现

在Java 5中,对于Integer的操作引入了一个新功能来节省内存和提高性能。整型对象通过使用相同的对象引用实现了缓存和重用。

适用于整数值区间-128 至 +127。 只适用于自动装箱。使用构造函数创建对象不适用。

这就要求我们具备Java的自动装箱和自动拆箱的知识。
简单一点说,装箱就是 编译器调用valueOf方法将基本数据类型转换为包装器类型(即对象);拆箱就是 编译器通过调用intValue(),doubleValue()等方法将包装器类型(对象)转换为基本数据类型

下图是基本数据类型对应的包装器类型:
Java基础:128陷阱之Integer缓存源码研究

注意:Integer、Short、Byte、Character、Long这几个类的valueOf方法的实现是类似的。
  Double、Float的valueOf方法的实现是类似的。
 为什么Double类的valueOf方法会采用与Integer类的valueOf方法不同的实现?
  因为在某个范围内的整型数值的个数是有限的,而浮点数却不是。


以Integer为例看一下其valueOf源码:

    /** * Returns an {@code Integer} instance representing the specified * {@code int} value. If a new {@code Integer} instance is not * required, this method should generally be used in preference to * the constructor {@link #Integer(int)}, as this method is likely * to yield significantly better space and time performance by * caching frequently requested values. * * This method will always cache values in the range -128 to 127, * inclusive, and may cache other values outside of this range. * * @param i an {@code int} value. * @return an {@code Integer} instance representing {@code i}. * @since 1.5 */
    public static Integer valueOf(int i) {
     
       
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

可以看出,当我们输入的 i 值在low和high范围内,就会去IntegerCache.cache中寻找,如果找不到则new一个


IntegerCache是Integer类中定义的一个private static的内部类。源码:

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

从上面两段代码可以看出,在自动装箱的情况下,缓存通过一个for循环实现。
从低到高创建整数存储在一个整数数组中。这个缓存会在Integer类第一次被使用的时候初始化出来。当通过valueOf方法创建对象的时候,如果数值在[-128,127]之间,便返回指向IntegerCache.cache中已经存在的对象的引用;否则创建一个新的Integer对象

需要注意最大值127不是固定的:

最大值127可以通过-XX:AutoBoxCacheMax=size修改。

实际上这个功能在Java 5中引入的时候,范围是固定的-128 至 +127。后来在Java 6中,可以通过java.lang.Integer.IntegerCache.high设置最大值。这使我们可以根据应用程序的实际情况灵活地调整来提高性能。到底是什么原因选择这个-128到127范围呢?因为这个范围的数字是最被广泛使用的。
在程序中,第一次使用Integer的时候也需要一定的额外时间来初始化这个缓存。


下面我们以一段代码为例来讲解:

public class Main {
     
       
    public static void main(String[] args) {
     
          
        Integer a1=59;
		int a2=59;
		Integer a3=Integer.valueOf(59);
		Integer a4=new Integer(59);
		System.out.println(a1==a2);
		System.out.println(a1==a3);
		System.out.println(a1==a4);
		System.out.println(a2==a2);
 	}
}

控制台会输出什么呢?

true
true
flase
true

我们来逐句研究一下:
当Integer a1=59 的时候,会调用 Integer 的 valueOf 方法,

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

这个方法就是返回一个 Integer 对象,只是在返回之前,看作了一个判断,判断当前 i 的值是否在 [-128,127] 区别,且 IntegerCache 中是否存在此对象,如果存在,则直接返回引用,否则,创建一个新的对象。

在这里的话,因为程序初次运行,没有 59 ,所以,直接创建了一个新的对象。

int a2=59 ,这是一个基本类型,存储在栈中。
Integer a3 =Integer.valueOf(59); 因为 IntegerCache 中已经存在此对象,所以,直接返回引用。
Integer a4 = new Integer(59) ;直接创建一个新的对象。

所以对于其运行结果分析:

System. out .println(a1== a2); 
//a1是Integer对象,a2是int,这里比较的是值.Integer会自动拆箱成int,然后进行值的比较。所以,为真。

System. out .println(a1== a3); 
//因为 a3 返回的是a1 的引用,所以,为真。

System. out .println(a3==a4); 
//因为 a4 是重新创建的对象,所以 a3,a4 是指向不同的对象,因此比较结果为假。

System. out .println(a2== a4);
// 因为 a2 是基本类型,所以此时 a4 会自动拆箱,进行值比较,所以,结果为真。

对于128陷阱有了了解!

值得参考的博客:

  • 深入剖析Java中的装箱和拆箱
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2024年04月12日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   3天前   13   0   0 java