Java architecture from Java foundation -- basic type cache pool concept

Keywords: Java

Take Integer for example

The differences between new Integer(123) and Integer.valueOf(123) are as follows:

new Integer(123) creates a new object every time;

Integer.valueOf(123) uses objects in the cache pool, and multiple calls get references to the same object.

Integer x = new Integer(123);
Integer y = new Integer(123);
System.out.println(x == y);    // false
Integer z = Integer.valueOf(123);
Integer k = Integer.valueOf(123);
System.out.println(z == k);   // true

The valueOf() method is relatively simple to implement, which is to determine whether the value is in the cache pool first, and if so, directly return the contents of the cache pool.

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

In Java 8, the size of Integer cache pool is - 128 ~ 127 by default.

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

The compiler calls the valueOf() method during the autoboxing process, so multiple Integer instances are created using autoboxing with the same value, and the same object is referenced.

Integer m = 123;
Integer n = 123;
System.out.println(m == n); // true

The buffer pool corresponding to the basic type is as follows:

  • boolean values true and false
  • all byte values
  • short values between -128 and 127
  • int values between -128 and 127
  • char in the range \u0000 to \u007F

When using the wrapper types corresponding to these basic types, you can directly use the objects in the buffer pool.
Other introductions

Posted by rxbanditboy1112 on Wed, 11 Dec 2019 13:03:44 -0800