I found that the caching mechanism is improved in jdk versions 1.6 or above jdk.
In jdk 1.5, the cache array in Integer is fixed, see
static final Integer cache[] = new Integer[-(-128) + 127 + 1];
In jdk version 1.6 or later, a method called getAndRemoveCacheProperties and the IntegerCache.high property have IntegerCache.high added to the Integer class.
as
// value of the java.lang.Integer.IntegerCache.high property (obtained during VM init)
private static String integerCacheHighPropValue; static void getAndRemoveCacheProperties() { if (!sun.misc.VM.isBooted()) { Properties props = System.getProperties(); integerCacheHighPropValue = (String)props.remove("java.lang.Integer.IntegerCache.high"); if (integerCacheHighPropValue != null) System.setProperties(props);
With this change, it is allowed to configure the maximum value for the cache and use the new cache range. ( -128 <= cachedValue <= highestValue ).
* Here are my questions: *
Q # 1 Why does the cache range use [-128 ~ 127] in jdk 1.5 or the default cache for jdk version 1.6 or higher? Is it just support bytes and char '\u0000'~ 'u007f' ?
Q # 2 What is the advantage of indicating a high value for the cache range in jdk version 1.6 or higher? Which appeal or sceen is suitable for us?
Please help me with these questions. Thank you so much in advance.
Below is the source code for IntegerCache and valueOf (int i) in the Integer class. It is just for reference.
jdk 1.5
private static class IntegerCache { private IntegerCache(){} static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } } public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) {
jdk 1.6
private static class IntegerCache { static final int high; static final Integer cache[]; static { final int low = -128; // high value may be configured by property int h = 127; if (integerCacheHighPropValue != null) { // Use Long.decode here to avoid invoking methods that // require Integer autoboxing cache to be initialized int i = Long.decode(integerCacheHighPropValue).intValue(); i = Math.max(i, 127); // Maximum array size is Integer.MAX_VALUE h = Math.min(i, Integer.MAX_VALUE - -low); } high = h; cache = new Integer[(high - low) + 1]; int j = low; for(int k = 0; k < cache.length; k++) cache[k] = new Integer(j++); } private IntegerCache() {} } public static Integer valueOf(int i) { if(i >= -128 && i <= IntegerCache.high) return IntegerCache.cache[i + 128]; else return new Integer(i); }