How large is the Integer cache?

Internal Java implementation and could not be configured, the range is from -128 to 127. You can check Javadocs or simply take a look at sources:

public static Integer valueOf(int i) {
         final int offset = 128;
         if (i >= -128 && i <= 127) { // must cache
             return IntegerCache.cache[i + offset];
         }
         return new Integer(i);
}

UPD. I was wrong (thx to Marco Topolnik). All of the above is related to older Java implementations. For Java 7 implementation could be achieved with system property:

-Djava.lang.Integer.IntegerCache.high=<size>

or JVM setting:

-XX:AutoBoxCacheMax=<size>

UPD. 2 java.math.BigInteger has hardcoded cache for values -16 <= x <= 16. From sources:

    private final static int MAX_CONSTANT = 16;
    private static BigInteger posConst[] = new BigInteger[MAX_CONSTANT+1];
    private static BigInteger negConst[] = new BigInteger[MAX_CONSTANT+1];
    static {
    for (int i = 1; i <= MAX_CONSTANT; i++) {
        int[] magnitude = new int[1];
        magnitude[0] = i;
        posConst[i] = new BigInteger(magnitude,  1);
        negConst[i] = new BigInteger(magnitude, -1);
    }
    }

    public static BigInteger valueOf(long val) {
        // If -MAX_CONSTANT < val < MAX_CONSTANT, return stashed constant
        if (val == 0)
            return ZERO;
        if (val > 0 && val <= MAX_CONSTANT)
            return posConst[(int) val];
        else if (val < 0 && val >= -MAX_CONSTANT)
            return negConst[(int) -val];
        return new BigInteger(val);
    }

Leave a Comment