"Go" Understanding the Java Integer cache policy

Source: Internet
Author: User

This article describes the knowledge of the Integer cache in Java. This is a feature introduced in Java 5 that helps save memory and improve performance. First look at a sample code that uses an integer that shows the caching behavior of the integer. Then we will learn the reason and purpose of this realization. You can guess the output of the following Java program first. Obviously, there are some small traps here, which is why we wrote this article.

1234567891011121314151617181920212223 package com.javapapers.java;public class JavaIntegerCache {    public static void main(String... strings) {         Integer integer1 = 3;        Integer integer2 = 3;        if (integer1 == integer2)            System.out.println("integer1 == integer2");        else            System.out.println("integer1 != integer2");        Integer integer3 = 300;        Integer integer4 = 300;        if (integer3 == integer4)            System.out.println("integer3 == integer4");        else            System.out.println("integer3 != integer4");    }}

Most people think the result of the above two judgments is false. Although their values are equal, the two if judgments are considered false because the objects are compared and the references to the objects are different. In Java, = = Compares an object reference, while equals compares a value. Therefore, in this example, different objects have different references, so you should return false when making comparisons. But oddly enough, two similar if conditions are judged to return different Boolean values.

Here is the actual output of the above code,

12 integer1 == integer2integer3 != integer4

An Integer cache implementation in Java

In Java 5, a new feature was introduced for the operation of Integer to save memory and improve performance. An integer object implements caching and reuse in an internal implementation by using the same object reference.

The above rules apply to integer intervals-128 to +127.

This integer cache policy is only useful when auto-boxing (autoboxing), and an integer object created with the constructor cannot be cached.

The process of automatically converting the original type to the encapsulated class by the Java compiler is called auto-boxing (autoboxing), which is equivalent to calling the ValueOf method

12 Integer a = 10; //this is autoboxingInteger b = Integer.valueOf(10); //under the hood

Now we know where the corresponding part of the JDK source code is implemented. Let's look at the source code of VALUEOF. The following is the code in JDK 1.8.0 build 25.

1234567891011121314151617181920 /**    * Returns an {<a href="http://www.jobbole.com/members/java12">@code</a> Integer} instance representing the specified    * {<a href="http://www.jobbole.com/members/java12">@code</a> int} value.  If a new {<a href="http://www.jobbole.com/members/java12">@code</a> Integer} instance is not    * required, this method should generally be used in preference to    * the constructor {<a href="http://www.jobbole.com/members/57845349">@link</a> #Integer(int)}, as this method is likely    * to yield significantly better space and time performance by    * caching frequently requested values.    *    * This method will always cache values in the range -128 to 127,    * inclusive, and may cache other values outside of this range.    *    * @param  i an {<a href="http://www.jobbole.com/members/java12">@code</a> int} value.    * @return an {<a href="http://www.jobbole.com/members/java12">@code</a> Integer} instance representing {<a href="http://www.jobbole.com/members/java12">@code</a> i}.    * <a href="http://www.jobbole.com/members/chchxinxinjun">@since</a>  1.5    */   public static Integer valueOf(int i) {       if (i &amp;gt;= IntegerCache.low &amp;amp;&amp;amp; i &amp;lt;= IntegerCache.high)           return IntegerCache.cache[i + (-IntegerCache.low)];       return new Integer(i);   }

The new Integer object is looked up in Integercache.cache before it is created. There is a dedicated Java class that is responsible for the caching of integers.

Integercache class

Integercache is a private static class in the Integer class. Let's take a look at this class and have more detailed documentation that can provide us with a lot of information.

1234567891011121314151617181920212223242526272829303132333435363738394041424344 /**     * Cache to support the object identity semantics of autoboxing for values between     * -128 and 127 (inclusive) as required by JLS.     *     * The cache is initialized on first usage.  The size of the cache     * may be controlled by the {<a href="http://www.jobbole.com/members/java12">@code</a> -XX:AutoBoxCacheMax=} option.     * During VM initialization, java.lang.Integer.IntegerCache.high property     * may be set and saved in the private system properties in the     * sun.misc.VM class.     */    private static class IntegerCache {        static final int low = -128;        static final int high;        static final Integer cache[];        static {            // high value may be configured by property            int h = 127;            String integerCacheHighPropValue =                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");            if (integerCacheHighPropValue != null) {                try {                    int i = parseInt(integerCacheHighPropValue);                    i = Math.max(i, 127);                    // Maximum array size is Integer.MAX_VALUE                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);                } catch( NumberFormatException nfe) {                    // If the property cannot be parsed into an int, ignore it.                }            }            high = h;             cache = new Integer[(high - low) + 1];            int j = low;            for(int k = 0; k &amp;lt; cache.length; k++)                cache[k] = new Integer(j++);            // range [-128, 127] must be interned (JLS7 5.1.7)            assert IntegerCache.high &amp;gt;= 127;        }        private IntegerCache() {}    }

Javadoc detailed description of this class is used to implement cache support, and supports automatic boxing between 128 and 127. The maximum value of 127 can be modified by-xx:autoboxcachemax=size the JVM's startup parameters. The cache is implemented through a for loop. Create as many integers as you can from small to large and store them in an array of integers named cache. This cache is initialized when the Integer class is used for the first time. Later, you can use the instance objects contained in the cache instead of creating a new instance (in case of automatic boxing).

In fact, when this feature is introduced in Java 5, the range is fixed-128 to +127. Later in Java 6, the maximum value is mapped to Java.lang.Integer.IntegerCache.high, and the maximum value can be set using the JVM's startup parameters. This allows us to flexibly adapt to the actual application to improve performance. What is the reason for choosing this range-128 to 127? Because the integer value of this range is the most widely used. It also takes a certain amount of extra time to initialize the cache when the first Integer is used in the program.

Caching behavior in the Java language specification

The Java Language Specification (JLS) in the Boxing Conversion section provides the following:

If the value of a variable p belongs to: 128 to 127 for integers (§3.10.1), True and False Boolean (§3.10.3), ' u0000′ to ' u007f ' characters (§3.10.4), when p is wrapped into a and B two objects, you can directly Use a = = B to determine if the values of a and B are equal.

Other cached objects

This caching behavior applies not only to integer objects. We have a similar caching mechanism for classes of all integer types.

Has bytecache for caching Byte objects

Have Shortcache for caching short objects

Have Longcache for caching Long objects

Have Charactercache for caching Character objects

The Byte,short,long has a fixed range: 128 to 127. For Character, the range is 0 to 127. Except the Integer can be changed by the parameter range, the others are not.

Original link: Javapapers translation: importnew.com-master Zhang digging the pit
Link: http://www.importnew.com/18884.html
[ Reprint please keep the source, translator and translation links.] ]

"Go" Understanding the Java Integer cache policy

Related Article

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.