Integer Cache Mechanism

Source: Internet
Author: User

Tag: the object first xca TPS has conf [] Get integer

Integer Cache Mechanism

Summary:

1. JDK 128 adds a caching mechanism for integer. The cache object is returned in the range of-127-(the maximum frequency of using integer values in this range, no new object will be added, so as long as the values in the cache range are equal, the returned objects will be automatically packed. After jdk1.6, you can set the JVM startup parameter (-XX: autoboxcachemax = size) to a maximum value of 127.
2. the integer cache is only valid during automatic packing. objects created using the constructor (new) do not trigger the cache.
3. cache is not required when int and integer are compared, because integer will be automatically split into int and then compared with Int. In this case, the comparison value is equal.

Details:
A common interview question for integer is

Integer I1 = 100; integer I2 = 100; integer J1 = 200; integer J2 = 200; system. out. println (I1 = I2); // output truesystem. out. println (J1 = J2); // outputs false

Our most basic understanding of integer is that integer is the packaging class of int, and it is the reference data type. The reference data type is compared with the memory address of the object with =.
Let's take a look at the i1 creation process (jdk1.8)
First, it will automatically pack the integer I1 = 100 (in fact, call the valueof method). Java will compile this section as integer I1 = integer. valueof (100), you can view the class file verification on your own.
Then let's look at the integer. valueof method:

public static Integer valueOf(int i) {        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)];        return new Integer(i);    }

 

We can clearly see that the value of integercache is taken from the value of integercache first, and the value of integercache. Low is outside the range of integercache. High, the new object is directly added (the new object will exist in the heap memory)

Let's take a look at the integercache class. The integercache is an integer Private Static class.

1/** 2 * cache to support the Object Identity semantics of autoboxing for values between 3 *-128 and 127 (aggressive) as required by JLS. 4*5 * the cache is initialized on first usage. the size of the cache takes effect for the first time. 6 * may be controlled by the {@ code-XX: autoboxcachemax = <size>} Option. you can set the maximum value of 7 * During VM initialization, Java. lang. integer. integercache. high Property 8 * may be set and saved In the private system properties in the 9 * sun. misc. VM class.10 */11 12 Private Static class integercache {13 static final int low =-128; 14 static final int high; 15 static final integer cache []; 16 17 static {18 // high value may be configured by property19 int H = 127; 20 string integercachehighpropvalue = 21 sun. misc. VM. getsavedproperty ("Java. lang. integer. integercache. high "); 22 if (integercacheh Ighpropvalue! = NULL) {23 try {24 int I = parseint (integercachehighpropvalue); 25 I = math. max (I, 127); 26 // maximum array size is integer. max_value27 H = math. min (I, integer. max_value-(-low)-1); 28} catch (numberformatexception NFE) {29 // if the property cannot be parsed into an int, ignore it.30} 31} 32 High = H; 33 34 cache = new integer [(high-low) + 1]; 35 Int J = low; 36 for (int K = 0; k <cache. length; k ++) 37 cache [k] = new INTEGER (J ++); 38 39 // range [-128,127] Must be interned (jls7 5.1.7) 40 assert integercache. high> = 127; 41} 42 43 private integercache () {}44}

 

The cache of integer is created and stored in an array through the for loop. The annotation already explains that the array will be initialized when the integer is used for the first time and understood in combination with the class loading sequence, when integer is used for the first time, the internal static class is initialized, and the static code block is executed and stored in the heap. There will be first penalty

Jdk1.5 source code reference

 1 private static class IntegerCache { 2         static final Integer[] cache = new Integer[256]; 3  4         static { 5             for (int i = 0; i < cache.length; i++) { 6                 cache[i] = new Integer(i - 128); 7             } 8         } 9     }10 11     public static Integer valueOf(int paramInt) {12         if ((paramInt >= -128) && (paramInt <= 127)) {13             return IntegerCache.cache[(paramInt + 128)];14         }15         return new Integer(paramInt);16     }

When integer and INT are compared with =, integer is automatically split (the intvalue () method is called) to int for comparison.
I1 = 100 will be compiled into i1.intvalue () = 100


Other cached objects
This cache action is not only applicable to integer objects. We have a similar cache mechanism for all integer classes.
Bytecache is used to cache byte objects
Shortcache is used to cache short objects.
Longcache is used to cache long objects.
Charactercache is used to cache character objects.
Byte, short, and long have a fixed range:-128 to 127. For character, the range is 0 to 127. Except integer, the range can be changed by parameters.

Refer to blog: 52473649

 

INT and INTEGER (basic type and packaging type)

Integer is the packaging type of int, the difference between the two is:

1. The initial value of int is 0, the initial value of integer is null, and all reference types are null;

2. integer is a reference type, and objects are stored in the heap. Int Is the Basic data type, and objects are stored in the stack;

Advantages of using the packaging class:

1. Integer encapsulates many processing methods for convenient operations, such as hexadecimal conversion (tobinarystring) and conversion between data types (tostring );

2. Solve the problem that some types do not support basic data types. For example, list can only receive reference types;

As for when to use the basic data type, when to use the packaging type depends on the specific needs, when only as a numerical value does not require more operations, the basic type can be used flexibly

Basic data types and corresponding packaging classes
Int -- integer
Float -- float
Double -- double
Byte -- byte
Long -- long
Char -- character
Boolean -- Boolean
Short -- short

 

Automatic Disassembly box

 

Integer Cache Mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.