探究Java自动拆装箱与Cache

什么是拆装箱

拆装箱是Java1.5引入的新特性,它是基本数据类型与包装类型的互相转化。

装箱:基本数据类型 => 包装类型
拆箱:包装类型 => 基本数据类型

JVM是如何实现拆装箱

一般情况下我们是不需要自己手动做拆装箱操作的,JVM会自动帮我们做。那么JVM究竟是怎么做的呢?我们通过例子去探究:

package zoro;

public class Test {
    public static void main(String[] args) {
        Integer i = 5;
        int j = i;
    }
}

从编码的经验告诉我们:

Integer i = 5,其实是JVM做了装箱操作;
int j = i,则是做了拆箱的操作。

我们不妨使用javap -c,剖析一下字节码:

Compiled from "Test.java"
public class zoro.Test {
  public zoro.Test();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: iconst_5
       1: invokestatic  #2                  // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       4: astore_1
       5: aload_1
       6: invokevirtual #3                  // Method java/lang/Integer.intValue:()I
       9: istore_2
      10: return
}

从反编译的信息很明显的看出例子中装箱调用的是Integer的静态方法valueOf(),而拆箱则调用了静态方法intValue()

相同套路的还有很多其他的包装类型,如Byte、Short、Long、Float、Double……总结起来就是:装箱使用valueOf(),拆箱使用xxxValue()

聊聊IntegerCache

看以下例子:

@Test
public void integerCacheTest() {

    Integer i1 = 100;
    Integer i2 = 100;
    Integer i3 = 200;
    Integer i4 = 200;

    System.out.println(i1 == i2); // true
    System.out.println(i3 == i4); // false
}

在不了解装箱的情况下,很多同学可能单纯的以为int i的装箱就是new Integer(i),然后蛮自信地回答两个输出都是false,因为通过new的对象分配在堆中,两个对象即便有相同的值,但它们的引用是不等的。

执行结果告诉我们,这样理解是不对的。

现在我们已经通过前面了解到了int装箱到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);
}

注释翻译:

返回一个表示指定的 int 值的 Integer 实例。如果不需要新的 Integer 实例,则通常应优先使用该方法,而不是构造方法 Integer(int),因为该方法有可能通过缓存经常请求的值而显著提高空间和时间性能。
此方法将始终缓存-128到127范围内的值,
包含,并且可能缓存此范围之外的其他值。

说明Integer是有缓存套路的,在缓存范围时取缓存中的值,否则才new。从代码上看主要是依靠Integer的私有静态内部类IntegerCache中的cache[]来实现缓存的。

我们不妨看cache[]是在哪里填充内容的:

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

注释翻译:

依JLS要求,缓存以支持对象的自动装箱,包括-128~127的值。
缓存在第一次使用时初始化。缓存的大小可以由xx:autoboxcachemax=size选项控制。
在虚拟机初始化期间,java.lang.integer.integercache.high属性可以设置并保存在sun.misc.vm类的私有系统属性中。

从代码上看缓存的最低值:-128,最高值是127。最高值是可以通过系统属性java.lang.integer.integercache.high设置的,如果未设置或低于127则取127,如果这值高于2147483518(Integer.MAX_VALUE - (-low) -1)则取2147483518。

IntegerCache.cache[]的赋值:
cache[0] = new Integer(-128);
cache[1] = new Integer(-127);
……
cache[254] = new Integer(126);
cache[255] = new Integer(127);

故Integer.valueOf()为什么要计算偏移量了:

return IntegerCache.cache[i + (-IntegerCache.low)];

现在回来看例子:

System.out.println(i1 == i2); // true
System.out.println(i3 == i4); // false

i1和i2的字面值都是100,这在IntegerCache的默认范围[-128, 127]里面,故都取自缓存,它们的引用相等;而i3和i4的字面值是200,不在缓存范围,那就会使用new Integer(200)去装箱,那i3和i4就是两个堆中对象的引用,它们当然不相等。

其他包装类型的Cache

除了包装类Integer实现了IntegerCache之外,有其他包装类实现了Cache吗?

有,还有ByteCache、ShortCache、LongCache和CharacterCache等等。

它们的默认范围分别是:

缓存类范围
ByteCache[-128,127]
ShortCache[-128,127]
IntegerCache[-128,127]
LongCache[-128,127]
CharacterCache[0,127]

除了IntegerCache可以改变范围外,其他都不行。有兴趣的可以看下源码。

你可能感兴趣:

参考:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值