Java Integer的缓存策略

Java5为Integer的操做引入了一个新的特性,用来节省内存和提升性能。整型对象在内部实现中经过使用相同的对象引用实现了缓存和重用。 上面的规则默认适用于整数区间 -128 到 +127(这个整数区间能够经过启动应用的虚拟机参数修改:-XX:AutoBoxCacheMax)。这种Integer缓存策略仅在自动装箱(autoboxing)的时候有用,使用构造器建立的Integer对象不能被缓存。Java 编译器把原始类型自动转换为封装类的过程称为自动装箱(autoboxing),这至关于调用 valueOf 方法。java

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

首先看代码:数组

public class TestInteger {
  public static void main(String[] args) {
    int i = 128;
    Integer i2 = 128;
    Integer i3 = new Integer(128);
    //Integer会自动拆箱为int,因此为true
    System.out.println(i == i2);
    System.out.println(i == i3);
    System.out.println("**************");
    Integer i5 = 127;//java在编译的时候,被翻译成-> Integer i5 = Integer.valueOf(127);
    Integer i6 = 127;
    System.out.println(i5 == i6);//true
    Integer i9 = 128;
    Integer i10 = 128;
    System.out.println(i9 == i10);//false
    Integer ii5 = new Integer(127);
    System.out.println(i5 == ii5); //false
    Integer i7 = new Integer(128);
    Integer i8 = new Integer(123);
    System.out.println(i7 == i8);  //false
  }
}
复制代码

首先,7行和8行输出结果都为true,由于Integer和int比都会自动拆箱(jdk1.5以上)。 12行的结果为true,而15行则为false。java在编译Integer i5 = 127的时候,被翻译成-> Integer i5 = Integer.valueOf(127);因此关键就是看valueOf()函数了。只要看看valueOf()函数的源码就会明白了。JDK源码的 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);
  }
复制代码

看一下源码你们都会明白,对于-128到127之间的数,会进行缓存,Integer i5 = 127时,会将127进行缓存,下次再写Integer i6 = 127时,就会直接从缓存中取,就不会new了。因此12行的结果为true,而15行为false。 对于17行和20行,由于对象不同,因此为false。 对于以上的状况总结以下:bash

  • 不管如何,Integer与new Integer不会相等。不会经历拆箱过程,i3的引用指向堆,而i4指向专门存放他的内存(常量池),他们的内存地址不同,因此为false
  • 两个都是非new出来的Integer,若是数在-128到127之间,则是true,不然为false。java在编译Integer i2 = 128的时候,被翻译成-> Integer i2 = Integer.valueOf(128);而valueOf()函数会对-128到127之间的数进行缓存
  • 两个都是new出来的,都为false
  • int和Integer(不管new否)比,都为true,由于会把Integer自动拆箱为int再去比

AutoBoxCacheMax参数

// IntegerCache,Integer类的内部类,注意它的属性都是定义为static final
private static class IntegerCache {
    //缓存的下界,-128,不可变
    static final int low = -128;
    //缓存上界,暂为null
    static final int high;
    //缓存的整型数组
    static final Integer cache[];

    static {
        // 缓存上界,能够经过JVM参数来配置
        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);
            //最大的数组值是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() {
    }
}
复制代码

-XX:AutoBoxCacheMax这个参数是设置Integer缓存上限的参数,在VM初始化期间java.lang.Integer.IntegerCache.high属性能够被设置和保存在私有的系统属性sun.misc.VM class中。理论上讲,当系统须要频繁使用Integer时,或者说堆内存中存在大量的Integer对象时,能够考虑提升Integer缓存上限,避免JVM重复创造对象,提升内存的使用率,减小GC的频率,从而提升系统的性能。 理论归理论,这个参数可否提升系统系统关键仍是要看堆中Integer对象到底有多少、以及Integer的建立的方式。若是堆中的Integer对象不多,从新设置这个参数并不会提升系统的性能。即便堆中存在大量的Integer对象,也要看Integer对象时如何产生的。函数

  1. 大部分Integer对象经过Integer.valueOf()产生。说明代码里存在大量的拆箱与装箱操做。这时候设置这个参数会系统性能有所提升。
  2. 大部分Integer对象经过反射,new产生。这时候Integer对象的产生大部分不会走valueOf()方法,因此设置这个参数也是无济于事。

JDK中其余相似的缓存

Integer的缓存上限能够经过Java虚拟机参数修改,Byte、Short、Long、Character的缓存则无法修改。性能

Byteui

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];
}
复制代码

Shortspa

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);
}
复制代码

Charactercode

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);
}
复制代码

示例:

public class AllCacheDemo {
    /**
     * 演示JDK内部缓存
     */
    public static void main(String[] args) {
        Integer a = 28;
        Integer b = 28;
        println(a == b);

        Byte c = 25;
        Byte d = 25;
        println(c==d);

        Short p=12;
        Short q=12;
        println(p==q);

        Long x=127L;
        Long y=127L;
        println(x==y);

        Character m='M';
        Character n='M';
        println(m==n);
    }

    public static void println(Object o){
        System.out.println(o);
    }
}
复制代码

做者:刘晓;花名:愚谷。

点击 阅读更多 查看更多详情

相关文章
相关标签/搜索