自动装箱与缓存


现象

有以下代码:

 1 public class Main {
2 public static void main(String[] args) {
3 Integer i1 = 127;
4 Integer i2 = 127;
5 Integer i3 = new Integer(127);
6 Integer i4 = new Integer(127);
7
8 System.out.println(i1 == i2);//true
9 System.out.println(i3 == i4);//false
10 }
11 }
控制台输出:
true
false,

我们知道,第3、4行发生了自动装箱,生成了Integer对象,并将对象的引用赋值给i1和i2,“==”比较的是对象的引用,控制台输出看,i1和i2保存了同一个Integer对象的引用。

下面对上述代码进行反编译:

/*
* Decompiled with CFR 0.149.
*/
package com.learn.java; public class Main {
public static void main(String[] args) {
Integer i1 = Integer.valueOf((int)127);
Integer i2 = Integer.valueOf((int)127);
Integer i3 = new Integer((int)127);
Integer i4 = new Integer((int)127);
System.out.println((i1 == i2 ? 1 : 0) != 0);
System.out.println((i3 == i4 ? 1 : 0) != 0);
}
}

从反编译结果看,Integer类自动装箱执行了valueOf方法。


本质

下面是Integer类中构造方法和ValueOf(int)方法的源码以及注释:

package java.lang;
import java.lang.annotation.Native;
public final class Integer extends Number implements Comparable<Integer> {
/**
* Constructs a newly allocated Integer object that represents the specified int value.
* 创建一个新的、包装了指定int数值的Integer实例。
* @params value - the value to be represented by the Integer object.
*/
public Integer(int value) {
this.value = value;
} /**
* Returns an Integer instance representing the specified int value. If a new Integer instance * is not required, this method should generally be used in preference to the constructor
* Integer(int), as this method is likely to yield significantly better space and time
* performance by caching frequently requested values.
* 返回一个包装了指定int数值的Integer实例。除非必须返回一个Integer实例,应该优先使用valueOf(int)方法而
* 不是Integer(int)方法。valueOf(int)方法通过事先缓存常用的数值,表现出更好的时间、空间性能。
*
* This method will always cache values in the range -128 to 127,inclusive, and may cache other
* values outside of this range.
* 默认情况下,缓存-128~127范围内的值,缓存范围可根据需要进行一定的调整。
*
* @param i - an int value.
* @return an 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);
}
}

下面是valueOf(int)方法中使用到的IntegerCache内部类的源码:

    /**
* 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
* {-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.
* 缓存在首次使用时完成初始化,缓存的范围(上界)可通过 -XX:AutoBoxCacheMax 配置。
*/
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);
// 127是缓存的最小上界
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() {}
}

上面源码中的信息可以总结为以下几点:

  1. valueOf(int)方法不一定返回新Integer实例的引用。如果int数值在缓存范围内,返回的是缓存中已经存在的Integer实例的引用,这意味着,在不同的地方,使用相同的int数值调用valueOf(int)方法,可能得到相同的引用。
  2. 缓存在第一次使用valueOf(int)方法时创建。所以第一次使用valueOf(int)方法需要消耗额外的时间。
  3. 默认情况下,缓存数值在-128~127范围内的实例。
  4. 可以使用参数调整缓存的上界。最大上界为Integer.MAX_VALUE,最小上界为127(默认为该值)
  5. 最多缓存Integer.MAX_VALUE个元素。

拓展

下面看看其他包装类有没有与Integer类一样的缓存机制。

1. Byte

public final class Byte extends Number implements Comparable<Byte> {

    public static Byte valueOf(byte b) {
final int offset = 128;
return ByteCache.cache[(int)b + offset];
} 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));
}
}
}

从源码看,Byte也有类似的缓存机制,但是缓存的范围是固定的。

2. Short

public final class Short extends Number implements Comparable<Short> {

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

从源码看,Short也有类似的缓存机制,但是缓存的范围是固定的。

3. Long

public final class Long extends Number implements Comparable<Long> {

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

从源码看,Long也有类似的缓存机制,但是缓存的范围是固定的。

4. Float

public final class Float extends Number implements Comparable<Float> {
public static Float valueOf(float f) {
return new Float(f);
}
}

从源码看,Float没有缓存机制。

5. Double

public final class Double extends Number implements Comparable<Double> {
public static Double valueOf(double d) {
return new Double(d);
}
}

从源码看,Double没有缓存机制。

Java自动装箱与缓存的更多相关文章

  1. java 自动装箱自动拆箱

    1.Java数据类型 在介绍Java的自动装箱和拆箱之前,我们先来了解一下Java的基本数据类型. 在Java中,数据类型可以分为两大种,Primitive Type(基本类型)和Reference ...

  2. Java 自动装箱与拆箱

    Java 自动装箱与拆箱(Autoboxing and unboxing)   什么是自动装箱拆箱 基本数据类型的自动装箱(autoboxing).拆箱(unboxing)是自J2SE 5.0开始提供 ...

  3. Java自动装箱和自动拆箱操作

    1.Java数据类型 在介绍Java的自动装箱和拆箱之前,我们先来了解一下Java的基本数据类型. 在Java中,数据类型可以分为两大种,Primitive Type(基本类型)和Reference ...

  4. java自动装箱拆箱总结

    对于java1.5引入的自动装箱拆箱,之前只是知道一点点,最近在看一篇博客时发现自己对自动装箱拆箱这个特性了解的太少了,所以今天研究了下这个特性.以下是结合测试代码进行的总结. 测试代码: int a ...

  5. 【转】java 自动装箱与拆箱

    java 自动装箱与拆箱 这个是jdk1.5以后才引入的新的内容,作为秉承发表是最好的记忆,毅然决定还是用一篇博客来代替我的记忆: java语言规范中说道:在许多情况下包装与解包装是由编译器自行完成的 ...

  6. Java进阶(三十七)java 自动装箱与拆箱

    Java进阶(三十七)java 自动装箱与拆箱 前言 这个是jdk1.5以后才引入的新的内容.java语言规范中说道:在许多情况下包装与解包装是由编译器自行完成的(在这种情况下包装称为装箱,解包装称为 ...

  7. JAVA基础之——三大特征、接口和抽象类区别、重载和重写区别、==和equals区别、JAVA自动装箱和拆箱

    1 java三大特征 1)封装:即class,把一类实体定义成类,该类有变量和方法. 2)继承:从已有的父类中派生出子类,子类实现父类的抽象方法. 3)多态:通过父类对象可以引用不同的子类,从而实现不 ...

  8. JAVA自动装箱拆箱与常量池

    java 自动装箱与拆箱 这个是jdk1.5以后才引入的新的内容,作为秉承发表是最好的记忆,毅然决定还是用一篇博客来代替我的记忆: java语言规范中说道:在许多情况下包装与解包装是由编译器自行完成的 ...

  9. java包装类的自动装箱及缓存

    首先看下面一段代码 public static void main(String[] args) { Integer a=1; Integer b=2; Integer c=3; Integer d= ...

随机推荐

  1. Java第十四天,集合、迭代器的使用

    集合 集合框架 一.Collection 1.定义方法: Collection<E> obj = new Collection子类<>(); 因为Collection是一个抽象 ...

  2. jQuery extend()和jQuery.fn.extend()区别和详解

    1.认识jQuery extend()和jQuery.fn.extend() jQuery的API手册中,extend方法挂载在jQuery和jQuery.fn两个不同对象上方法,但在jQuery内部 ...

  3. spark error Caused by: java.io.NotSerializableException: org.apache.hadoop.hdfs.DistributedFileSystem

    序列化问题多事rdd遍历过程中使用了没有序列化的对象. 1.将未序列化的变量定义到rdd遍历内部.如定义入数据库连接池. 2.常量定义里包含了未序列化对象 ,提出去吧 如下常量要放到main里,不能放 ...

  4. python3(二十七)property

    """ """ __author__ = 'shaozhiqi' # 绑定属性时,如果我们直接把属性暴露出去,虽然写起来很简单, # 但是, ...

  5. Docker命名空间

    命名空间 命名空间( namespace )是 Linux 内核的一个强大特性,为容器虚拟化的实现带来极大便利,利用这 特性,每个容器都可以拥有自己单独的命名空间,运行在其中的应用都像是在独立的操作系 ...

  6. 运行jmeter.bat时 提示 not able to find java executable or version

    安装过好几次,这是第一次遇到运行jmeter.bat时 提示 not able to find java executable or version Please check your Java in ...

  7. Linux c++ vim环境搭建系列(2)——Ubuntu18.04.4编译安装llvm clang

    2. 源码编译安装llvm clang 参考网址: https://llvhttps

  8. AJ学IOS 之微博项目实战(3)微博主框架-UIImage防止iOS7之后自动渲染_定义分类

    AJ分享,必须精品 一:效果对比 当我们设置tabBarController的tabBarItem.image的时候,默认情况下会出现图片变成蓝色的效果,这是因为ios7之后会对图片自动渲染成蓝色 代 ...

  9. AJ学IOS(47)之网易彩票帮助界面UIWebView的运用

    AJ分享,必须精品 效果: 制作过程 首先是帮助按钮那个地方的点击. 这里是用点击跳转的用的是 NJSettingArrowItem,前面的设置的,从字典通过模型转过来的. // 分享 NJSetti ...

  10. V - Infinite Prefixes CodeForces - 1295B math

    天哪!!菜到家啦. 数学+思维. 首先求出一个周期内cnt0-cnt1=c的个数,如果C=0,那么只要在一个周期内有前缀等于x,那么答案就是-1,否则答案就是0 如果C!=0,列一下方程x=t*c+a ...