//虚拟机配置了相关的最大缓存 -XX:AutoBoxCacheMax=1000Class clazz = Class.forName("java.lang.Integer$IntegerCache");Field f = clazz.getDeclaredField("cache");f.setAccessible(true);System.out.println(Arrays.toString((Integer[])f.get("cache")));f.setAccessible(false);//-XX:AutoBoxCacheMax=1000Integer i = 800;Integer j = 800;System.out.println(i == j);
java.lang.Integer$IntegerCache
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's 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() {} }
private static class ShortCache { private ShortCache(){} static final Short cache[] = new Short[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Short((short)(i - 128)); } }
private static class LongCache { private LongCache(){} static final Long cache[] = new Long[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Long(i - 128); } }