자바 의 성형 캐 시 메커니즘

4267 단어 Java
본 고 는 자바 에서 Integer 에 관 한 캐 시 지식 을 소개 할 것 입 니 다.먼저 아래 코드 를 보고 어떤 결 과 를 출력 할 지 추측 해 보 겠 습 니 다.
/**
 * Created by lanxing on 16-3-13.
 */
public class IntegerCache {
    public static void main(String[] args){
        Integer integer1 = 3;
        Integer integer2 = 3;
        System.out.println(integer1 == integer2);

        Integer integer3 = 300;
        Integer integer4 = 300;
        System.out.println(integer3 == integer4);
    }
}

상기 코드 에 대해 서 는'='을 사용 하고 자바 에서'=='은 인용 이 아 닌 두 개의 인용 값 을 비교 하기 때문에 두 출력 이 모두 false 라 고 생각 하지만 실행 결 과 는 true,false 입 니 다.
Java 에서 Integer 캐 시 메커니즘 에 대한 소개:
상기 코드 가 자동 패키지 작업 을 진행 하 였 기 때문에 자바 의 Integer 소스 코드 의 value Of(int)코드 는 다음 과 같 습 니 다.
    /**
     * 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);
    }
상기 소스 코드 를 통 해 알 수 있 듯 이 포장 대상 이 Integer Cache.low 에서 Integer.high 사이 에 있 을 때 결 과 는 Integer Cache 에서 직접 얻 을 수 있 습 니 다.그렇지 않 으 면 인 스 턴 스 를 직접 만 듭 니 다.다음은 Integer 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=} 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;
        }
상기 소스 코드 를 분석 한 결과 IntegerCache 의 low 는-128 이 고 하 이 는'-XX:AutoBoxCacheMax='을 통 해 지정 할 수 있 으 며 기본 적 인 하 이 는 127 이다.하 이 를 설정 한 후,하 이 의 실제 값 은 기본 값 과 설정 값 중 최대 값 을 가 져 오 며,동시에 0x7FFF7E 보다 작 거나 같 습 니 다.그리고 low 에서 high 사이 의 수 치 를 cache 에 저장 합 니 다.이 클래스 와 방법 은 모두 정적 이기 때문에 처음 사용 할 때 이 동작 을 수행 합 니 다.low 에서 high 사이 의 숫자 를 패키지 작업 을 해 야 할 때 IntegerCache.cache 에서 기 존 참조 로 돌아 갑 니 다.따라서 상기 기본 유형 3 을 포장 할 때 같은 인용 을 되 돌려 주 므 로 결 과 는 true 를 출력 합 니 다.
물론 자바 에는 Integer 에 대한 캐 시 메커니즘 을 제외 하고 ByteCache,ShortCache,LongCache,CharacterCache 가 각각 해당 하 는 유형 에 대해 캐 시 를 한다.그 중에서 Byte,Short,Long 의 캐 시 범 위 는 모두-128-127 이 고 Character 는 0-127 이다.특히 주의해 야 할 것 은 이 몇 개의 캐 시 중 Integer 의 캐 시 상한 선(high)만 설정 할 수 있 고 다른 것 은 설정 할 수 없 으 며 고정 범위 입 니 다.

좋은 웹페이지 즐겨찾기