Technology Inside Out!

Index ¦ Archives ¦ Atom ¦ RSS

Java: Autoboxing and -XX:AutoBoxCacheMax

Autoboxing is the mechanism in Java to convert primitive type values to respective wrapper class object. Java programmer mostly use autoboxing while using collections, since collection only holds object and to put primitive type data into collection, it's need to use wrapper classes to convert into objects.

So , here is autoboxing to assign primitive type to wrapper type directly.

  • boolean to type Boolean
  • byte to type Byte
  • short to type Short
  • char to type Character
  • int to type Integer
  • long to type Long
  • float to type Float
  • double to type Double

You can directly compare wrapper classes using

== ,

just like primitive types but

for certain range which is by default (-128 to 127) .Which is default value of 

-XX:AutoBoxCacheMax .

Here is the demo program when your object which is a autoboxed primitive type can be compared directly.

        int int1 = 100;
        int int2 = 100;
        System.out.println(int1 == int2);    // true as they are primitive

        Integer integerObj1 = new Integer(100);
        Integer integerObj2 = new Integer(100);
        System.out.println(integerObj1 == integerObj2);   // always false as these are objects 

        Integer integer1 = 100;
        Integer integer2 = 100;
        System.out.println(integer1 == integer2);   // true

        Character c1 = 110;
        Character c2 = 110;
        System.out.println(c1 == c2);    //true

        Short s = 56;
        Short s1 = 56;
        System.out.println(s == s1);    //true

 Why caching this range :

This short range are generally used and  performance of

public static valueOf( i)

  as this method is likely to yield significantly better space and time performance by caching frequently requested values.

 Changing  -XX:AutoBoxCacheMax :

You can set the -XX:AutoBoxCacheMax=1000, and it will catch integer upto 1000 which means following code will results true

Integer integer1 = 1000;
        Integer integer2 = 1000;
        System.out.println(integer1 == integer2);   // true

Note: this changing size only works for positive integer and it can't be set less than 127.  See inner class

private static class IntegerCache


Setting Runtime VM option in Eclipse,

Max size of -XX:AutoBoxCacheMax ;

Max cache size can't be more than -Xmx (which is JVM heap size) . Heap size is defined by vm argument -Xmxm .
But, you as soon as JVM initialized, it allocate the memory for caching purpose. But you can't allocate whole (-Xmx in byte)/4 (4byte is size of  int) for AutoBoxCache because of other object needed to be loaded and you might end up with

java.lang.OutOfMemoryError: Java heap space


Also, note that for other wrapper classes except Integer , have fixed caching size upto 127 only.

© The Geeky Way. Built using Pelican. Theme by Giulio Fidente on github.

Disclaimer Privacy policy