This is the 24th day of my participation in the August More Text Challenge

This is one of the most common interview questions in the world.

IntegerCache, which in its name is a cache of integer data, is also very much like a cache in its function.

Let’s start with a related question that often appears in pen-based exams.

public class IntegerTest { public static void main(String [] args) { Integer a = 100, b = 100 ,c = 129,d = 129; System.out.println(a==b); System.out.println(c==d); }}Copy the code

There are usually a few more options, but we won’t talk about them here, just what the output is.

First, the correct answer:

true
false
Copy the code

Why does this happen? Of course, that’s what IntegerCache is for. As I said, it provides caching, but what does it actually cache?

By default, IntegerCache caches an Integer ranging from -128 to 127. All data in this range is directly obtained from IntegerCache without creating a new object.

This can also be easily seen in the Integer source code.

The specific code is as follows:

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

    private IntegerCache(a) {}}Copy the code

This is an inner class in the Integer class that defines a cache of commonly used values, with a range of numeric sizes that can be specified.

From can also be seen in the code, the code for a integerCacheHighPropValue value, after that, the value again after conversion, select a maximum value with 127.

. That is to say, if I set up the Java lang. Integer. IntegerCache. This option is high, also can enlarge the cache area space.

sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high")

That this value is how to configure, the answer is – Djava. Lang. Integer. IntegerCache. High