首先,我们都知道integer在-128至127(包含),是走缓存的,该缓存设计目的是:节省内存,提高性能。

猜想,Long是否也存在类似缓存设计?

public static void main(String[] args) {
    Integer integer1 = 3;
    Integer integer2 = 3;
    System.out.printf("integer1 == integer2:[%s]\n", integer1 == integer2);

    Integer integer3 = 300;
    Integer integer4 = 300;
    System.out.printf("integer3 == integer4结果:[%s]\n", integer3 == integer4);

    System.out.println("--------换行----------");
    Long long1 = 3L;
    Long long2 = 3L;
    System.out.printf("long1 == long2:结果:[%s]\n", long1 == long2);

    Long long3 = 300L;
    Long long4 = 300L;
    System.out.printf("long3 == long4:结果:[%s]\n", long3 == long4);
}

返回值如下:

integer1 == integer2:[true]
integer3 == integer4结果:[false]
--------换行----------
long1 == long2:结果:[true]
long3 == long4:结果:[false]

剖析

剖析integer

java.lang.integer类中有个private static class IntegerCache静态内部类。其javadoc如下:

/**
     * 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.
     */

其最大值(high)可以通过-XX:AutoBoxCacheMax=<size>属性来指定,但代码中有判断,确保其不可小于127

剖析Long

java.lang.Long类中有个private static class LongCache静态内部类。其代码如下:

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

参考链接

下面这段文字,来自:https://github.com/hollischuang/toBeTopJavaer/blob/master/basics/java-basic/integer-cache.md

这种缓存行为不仅适用于Integer对象。我们针对所有的整数类型的类都有类似的缓存机制。

ByteCache用于缓存Byte对象
ShortCache用于缓存Short对象
LongCache用于缓存Long对象
CharacterCache用于缓存Character对象
07-14 18:19