How to modify integercache in Java 9

Before starting the body of this article, let's take a look at the following code:

The role of integercache of integer class in Java

Package name: Java lang

File name: integer java

Method name: integercache

The code of the method is as follows:

We can see in the code that low is - 128 and high is 127. In this way, in Java programming, if you want to use objects in the range of - 128 -- 127, you can directly use the objects in the cache.

The above is a brief introduction to help you understand integercache. Let's start the text of this article:

introduction

Five years ago, I published an article on how to change integercache in JDK on Hungarian. This approach is actually going deep into the Java runtime, which is not actually used in the scene. When you develop this research code, you can better understand how reflection works and how the integer class is implemented.

The integer class has a private nest called integercache that contains integer objects with values from - 127 to 128.

When the code needs to be boxed from int type to integer object and the value is within this range, the Java runtime will use this cache instead of creating a new integer object. This is mainly due to the consideration of performance optimization. We must keep in mind that many int values are in this range many times in the program (such as the subscript index of the array).

The side effect of this is that many times, when using the equal sign operator to compare two integer objects, as long as the value is within the range, it is valid. This is typical in unit testing. In the run mode, when the value is greater than 128, the code execution will fail.

Using reflection to access the integercache class can cause some strange side effects. Note that this will affect the entire JVM. If a servlet redefines a small integer cache value, all other servlets running under the same Tomcat will encounter the same problem.

There are other articles on Lukas Eder and Sitepoint that describe this problem.

This article is translated from: https://dzone.com/articles/hacking-the-integercache-in-java-9

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>