Example Analysis of Integer IntegerCache Source Code
This article mainly introduces the Integer Integer Cache source code sample analysis, the text is very detailed, has a certain reference value, interested friends must read!
Let's look at the test results:
/*public static void main(String[] args) { Integer a = 128, b = 128; Integer c = 127, d = 127; System.out.println(a == b);//false System.out.println(c == d);//true }*/ /*public static void main(String[] args) { Integer int1 = Integer.valueOf("100"); Integer int2 = Integer.valueOf("100"); System.out.println(int1 == int2);//true }*/ public static void main(String[] args) { Integer int1 = Integer.valueOf("300"); Integer int2 = Integer.valueOf("300"); System.out.println(int1 == int2);//false }
The source code of JDK is as follows:
public static Integer valueOf(String s) throws NumberFormatException { return Integer.valueOf(parseInt(s, 10)); }public static Integer valueOf(int i) { if (i >= IntegerCache.low && i = 127; } private IntegerCache() {} }
Integer instantiates integers from-128 to 127 (adjustable) in advance.
This explains the answer. It turns out that no matter how many Integer you create in this range, ValueOf is the same object.
But why does JDK have to go to all this trouble? We think carefully, most of Taobao's goods are within 100 prices, a day background server will be new how many of this Integer, using IntegrCache, it reduces the time of new and improves efficiency. JDK also provides configurable cache values.
This certainly increases flexibility and facilitates optimization of the JVM.
Above is "Integer Integer Cache source code sample analysis" all the content of this article, thank you for reading! Hope to share the content to help everyone, more relevant knowledge, welcome to pay attention to the industry information channel!