SoFunction
Updated on 2025-04-05

Java's Integer cache pool usage

Java's Integer buffer pool?

Integer cache pools are mainly used to improve performance and save memory. According to practice, most data operations are concentrated in a range with relatively small values, so caching these objects can reduce the burden of memory allocation and garbage collection and improve performance.

Integer objects in the range -128 to 127 will be cached and multiplexed.

principle

int will be called when autoboxing, and then use IntegerCache.

@HotSpotIntrinsicCandidate
public static Integer value0f(int i){
    if(i>=  && i<= )  //If the int value is within the cache range, the Integer object will be returned directly from the cache        return [i+(-)];
    return new Integer(i);                              // Otherwise, create a new Integer object}
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 = ( key:"");
        if(integerCacheHighPropValue != null){
            try {
                int i = parseInt(integerCacheHighPropValue);
                i = (i,127);
                // Maximum array size is Integer.MAX_VALUE
                h= (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 i = low;
        for(int k=0;k< ; k++)    //Transfer all objects created -128-127            cache[k]= new Integer(i++);
        assert  >= 127;
    }
    
    private IntegerCache(){}
}

So there is another interview question here: Why are the ones within Integer 127 equal and those exceeding 127 no longer waiting?

Because it is less than or equal to 127IntegerObjects are retrieved from the same cache pool, they point to the same object instance, so their references are equal.

Not only Integer, Long also has a cache pool, but the range is written from -128 to 127 and cannot be adjusted through JVM parameters.

@HotSpotIntrinsicCandidate
public static Long value0f(long l){
    final int offset = 128;
    if(l>= -128 &&l<= 127){ // will cache
        return [(int)l + offsetl];
    }
    return new Long(l);
}

Summarize

  • Byte, Short, Integer, and Long, the four packaging classes, create corresponding types of cache data with the value [-128, 127] by default.
  • Character creates cached data with values ​​in the range [0,127]
  • Boolean Returns True or False directly
  • Float and Double do not have cached data, after all, they are decimals, so there are too many numbers that can be saved.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.