Instance Cache

์ž๋ฐ”์˜ wrappingํƒ€์ž…์ด ๊ฐ’์„ ์ดˆ๊ธฐํ™” ํ•˜๋Š” ๋ฐฉ์‹์— ๋Œ€ํ•ด ์„ค๋ช…ํ•ฉ๋‹ˆ๋‹ค. Integer.valueof()๋กœ ์„ค๋ช…ํ•ฉ๋‹ˆ๋‹ค

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }
    
private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        ...
        ...

์ง์ ‘ Cache ์‚ฌ์ด์ฆˆ๋ฅผ ์ง€์ •ํ•ด ๋‘์ง€ ์•Š๋Š”๋‹ค๋ฉด -127~128(1byte) ๋งŒํผ์„ ์บ์‹œํ•ด๋‘ก๋‹ˆ๋‹ค.

    public static void main(String[] args) throws IOException, InterruptedException {
        Integer add1 = Integer.valueOf(1);
        Integer add2 = Integer.valueOf(1);

        System.out.println("same ? :" + (add2 == add1));
        //same ? :true
        Integer add3 = Integer.valueOf(258);
        Integer add4 = Integer.valueOf(258);

        System.out.println("same ? :" + (add3 == add4));
        //same ? :false
    }

์บ์‹œ ๋ฒ”์œ„์— ์žˆ๋Š” add1, add2์€ ๊ฐ’์€ ์ธ์Šคํ„ด์Šค ์บ์‹œ ๋ฒ”์œ„ ๋ฐ”๊นฅ์— ์žˆ๋Š” add3, add4๋Š” ๋‹ค๋ฅธ ์ธ์Šคํ„ด์Šค์ธ๊ฑธ ํ™•์ธ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

-XX:AutoBoxCacheMax=size ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ, ๋ฒ”์œ„(-127 ~ size)๋ฅผ ์ง์ ‘ ์ง€์ •ํ•ด์ค„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค

Integer cache ์ด์™ธ์—๋„ ByteCache, ShortCache, LongCache, CharcaterCache๊ฐ€ ๊ฐ™์€ ๋ฐฉ์‹์œผ๋กœ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.

Last updated