Java自动装箱和拆箱,包装类缓存机制和JVM调节

2017-05-31  本文已影响337人  远o_O

关于Java自动装箱和拆箱

/**
     * 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) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    /**
     * Returns the value of this {@code Integer} as an
     * {@code int}.
     */
    public int intValue() {
        return value;
    }

基本类型防迷惑

        /**
         * 基本类型不管多大,==都返回true,因为基本类型不会比较地址,更不存在equals
         */
        int a1 = 121,a2 = 121;
        int b1 = 128,b2 = 128;
        System.out.println(a1 == a2);//true
        System.out.println(b1 == b2);//true

包装类所提供的缓存机制

        //Integer
        Integer l1 = 12;
        Integer l2 = 12;
        Integer l3 = 128;
        Integer l4 = 128;
        System.out.println(l1 == l2);//true
        System.out.println(l3 == l4);//false
        //Long
        Long l5 = 128L;
        Long l6 = 128L;
        System.out.println(l5 == l6);//false
        Double d1 = 12d;
        Double d2 = 12d;
        System.out.println(d1 == d2);//false
    /**
     * 调节虚拟机参数:-XX:AutoBoxCacheMax=250后,最大缓存值可以达到-128——250
     */
    @org.junit.Test
    public void test2(){
        Integer l3 = 250;
        Integer l4 = 250;
        System.out.println(l3 == l4);//true
    }
    /**
     * Compares this object to the specified object.  The result is
     * {@code true} if and only if the argument is not
     * {@code null} and is an {@code Integer} object that
     * contains the same {@code int} value as this object.
     *
     * @param   obj   the object to compare with.
     * @return  {@code true} if the objects are the same;
     *          {@code false} otherwise.
     */
    public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }
  /**
     * 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.
     */

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

再看一下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];
        }
        //否则直接返回new出来的
        return new Long(l);
    }
上一篇 下一篇

猜你喜欢

热点阅读