5

In Integer class, there is private static class IntegerCache.

What is the use of this class?

What are the benefits of it while using Integer?

0

3 Answers 3

9

Values between -128 and 127 are cached for reuse. This is an example of the flyweight pattern, which minimizes memory usage by reusing immutable objects.


Beyond being an optimization, this behaviour is part of the JLS, so the following may be relied upon:

Integer a = 1;
Integer b = 1;
Integer c = 999;
Integer d = 999;
System.out.println(a == b); // true
System.out.println(c == d); // false
0
5

IntegerCache caches value between -128 to +127 to optimise Autoboxing.

You can set upper bound greater than 127 using -XX:AutoBoxCacheMax=NEWVALUE or -Djava.lang.Integer.IntegerCache.high=NEWVALUE

3

Look at its implementation:

private static class IntegerCache {
   static final int high;
   static final Integer cache[];
   static {
      final int low = -128;
      int h = 127;
      if (integerCacheHighPropValue != null) {
          int i = Long.decode(integerCacheHighPropValue).intValue();
          i = Math.max(i, 127);
          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() {}
}

256 values are cached to be used again, they'll be loaded when you create the first Integer object.

So when you use the == operator to check the equality for two Integers on the range of [-127,128], you'll get it as if you where comparing two ints. But if you compare two Integers out of this range using ==, you'll get false, even if they have the same value.

Not the answer you're looking for? Browse other questions tagged or ask your own question.