Monday, 8 April 2019

Integer Cache

Where does Java store Integers and other Wrapper classes? Its always the heap. But, Integer.valueOf(100) will always return the same instance but Integer.valueOf(200) will always return a new instance. Why this difference.

There is an IntegerCache in java.lang.Integer which stores instances for values -128 though 127. This means that Integer.valueOf(17) always will return the very same instance, while Integer.of(200) will not. While this clearly has the advantage of reuse of commonly used Integer values which results in better performance, thus relieving the GC from some work, it also has implications for autoboxing and identity comparisons.

The boundaries of this IntegerCache can be changed using  -XX:AutoBoxCacheMax=  <new value>.

The cache always has these 256 Integer values closest to 0 pre-filled rather than populating it on demand. So if the boundaries are tweaked, then this could impact memory consumption.

No comments:

Post a Comment

Volatile keyword, Synchronized keyword and Lock interface

Volatile Marking a member variable as volatile, makes sure, when ever the member variable is accessed, its value is always read from the...