This is the topic we are going to discuss today because I think it is very interesting. If you run the following code:
You will get the following result:
We know that if two references point to the same object, then == is true; conversely, if the two references do not point to the same object, then == is not true, even if the contents of the two references are the same. Therefore, the result will be false. This is where it gets really interesting. If you look inside the Integer.java class, you’ll find an inner private class called IntegerCache.java that provides a cache for all integer objects between -128 and 127. This thing provides an internal cache for small integers, and when declared like this:
This is what it looks like inside:
In fact, after I decompile the A.class file, the code is as follows: If we look at the valueOf() class function, we can see:
If the value is between -128 and 127, it returns an instance of that cache. therefore...
Both refer to the same object. That's why the following code evaluates to true:
Now you might ask, why would there be a cache for all integers between -128 and 127? This is because the frequency of use of small integers in this range is much greater than that of other integers in daily life, and the fact that the same underlying object is used multiple times can be effectively optimized for memory through this setting. You can use this feature arbitrarily using the reflection API. Run the following code and you will see the magic.
The print result is:
Let's look at the disassembled code again: Is this the same problem as above? But why is the result 2 + 2 = 5? Let's continue to look at the Integer source code to gain a deeper understanding of the Integer cache mechanism. Here is a screenshot: According to the source code, we can find that the method of modifying the upper limit of the Integer cache has some minor flaws. Let's take a look at what the API suggests to us:
It turns out that we only need to set -XX:AutoBoxCacheMax=133 at runtime. |
<<: Android performance optimization memory leak
>>: How to use fastboot to flash the original image to Android
In the Internet era, consumer decision-making pat...
Before reading this article, novice SEOs can revi...
All major automakers are making driverless cars. ...
On the 25th, Chinese technology giant Huawei sued...
According to the user life cycle, users can be di...
It took only two years for Chinese auto brands to...
In the process of optimizing the website, if the ...
There is a long-standing rumor that a peasant wom...
A brief study on the “Jiuxiao Huanpei” zither col...
When it comes to the factors that can affect keyw...
Anyone who has done a little research on short vi...
Produced by: Science Popularization China Author:...
The sweet potatoes roll happily in the pot and so...
When Lucid unveiled the prototype of its new Air e...
Lucky draw activities are an important tool for i...