Understanding Java Wrapper Class Caching Mechanisms
Java's wrapper classes implement caching mechanisms to optimize performance for commonly used values. Several numeric wrapper classes cache values within specific ranges:
Byte,Short,Integer, andLongcache values between -128 and 127Charactercaches values from 0 to 127Booleandirectly returns eitherTRUEorFALSEinstances
Integer caching implementation:
public static Integer valueOf(int num) {
if (num >= IntegerCache.minVal && num <= IntegerCache.maxVal) {
return IntegerCache.cachedValues[num + (-IntegerCache.minVal)];
}
return new Integer(num);
}
private static class IntegerCache {
static final int minVal = -128;
static final int maxVal;
static final Integer[] cachedValues;
static {
int upper = 127;
// Configuration logic for upper bound would go here
maxVal = upper;
cachedValues = new Integer[(maxVal - minVal) + 1];
for (int k = 0; k < cachedValues.length; k++) {
cachedValues[k] = new Integer(minVal + k);
}
}
}
The valueOf() method first checks if the input falls within the cached range. If so, it returns a pre-allocated object from the cache array. The array index calculation accounts for negative numbers by offsetting with the minimum cache value.
Character caching example:
public static Character valueOf(char ch) {
if (ch <= 127) {
return CharacterCache.predefinedChars[(int)ch];
}
return new Character(ch);
}
private static class CharacterCache {
static final Character[] predefinedChars = new Character[128];
static {
for (int i = 0; i < predefinedChars.length; i++) {
predefinedChars[i] = new Character((char)i);
}
}
}
Boolean optimization:
public static Boolean valueOf(boolean flag) {
return flag ? Boolean.TRUE : Boolean.FALSE;
}