The caching mechanism of integral type in Java

Source: Internet
Author: User

Source: Zhang Hongliang Source: Java Papers

This article describes the cache-related knowledge of Integer in Java. This is a feature that has been introduced in Java 5 to help save memory and improve performance. First look at a sample code that uses an integer to learn its caching behavior. Then why do we do that and how does he do it? Can you guess the output of the following Java program? If your results are not the same as the real results, then you should take a good look at 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");    }}

We generally believe that the result of the above two judgments is false. Although the comparison 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, the == comparison is the object application, and equals the comparison is the value. So, in this case, different objects have different references, so the comparison will return false. Oddly, here are two similar if conditions that determine the return of different Boolean values.

The actual output of the above code is:

12 integer1 == integer2integer3 != integer4
The cache implementation of Integer in Java

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

Applies to integer values range-128 to +127.

Applies to automatic boxing only. Creating objects using constructors does not apply.

The process of automatically converting basic data types to encapsulated class objects by the Java compiler is called 自动装箱 , equivalent to the method of use valueOf :

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

Now that we know where this mechanism is used in the source code, let's look at the methods in the JDK valueOf . Here is JDK 1.8.0 build 25 the implementation:

1234567891011121314151617181920 /**     * Returns an {@code Integer} instance representing the specified     * {@code int} value.  If a new {@code Integer} instance is not     * required, this method should generally be used in preference to     * the constructor {@link #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 {@code int} value.     * @return an {@code Integer} instance representing {@code i}.     * @since  1.5     */    public static Integer valueOf(int i) {        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)];        return new Integer(i);    }

Look in the Integercache.cache before creating the object. Use new to create a new object if it is not found.

Integercache Class

Integercache is an inner class defined in the integer class private static . Next look at his definition.

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 {@code -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 < cache.length; k++)              cache[k] = new Integer(j++);          // range [-128, 127] must be interned (JLS7 5.1.7)          assert IntegerCache.high >= 127;      }      private IntegerCache() {}  }

The Javadoc detailed description of the cache support-the automatic boxing process between 128 and 127. The maximum value of 127 can be -XX:AutoBoxCacheMax=size modified by. The cache is implemented through a for loop. From low to high and create as many integers as possible and store them in an array of integers. 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, this feature was introduced in Java 5 with a fixed range of 128 to +127. Later in Java 6, you can java.lang.Integer.IntegerCache.high set the maximum value. This allows us to flexibly adapt to the actual application to improve performance. What is the reason for choosing this-128 to 127 range? Because the number of this range is the most widely used. In a program, the first time an integer is used, it also takes some extra time to initialize the cache.

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 is:

-Integers between 128 and 127 (§3.10.1)

Boolean value of True and False (§3.10.3)

Characters between ' \u0000 ' and ' \u007f ' (§3.10.4)

When you wrap p as a and B two objects, you can use A==B to determine whether 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 all classes of 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

Byte, Short Long with a fixed range: 128 to 127. For Character , the range is 0 to 127. Apart from Integer that, this range cannot be changed.

Ask!-Customized IT education platform, one-to-man service, ask a question, develop programming social Headlines official website: www.wenaaa.com Download ask Ah app, participate in the official reward, earn hundred yuan cash.

QQ group 290551701 gathers a lot of Internet elite, technical director, architect, project Manager! Open source technology research, Welcome to the industry, Daniel and beginners are interested in engaging in IT industry personnel to enter!

The caching mechanism of integral type in Java

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.