Immutable class with instance cache in Java

Source: Internet
Author: User

The state of an instance of an immutable class does not change, such instances can be safely shared by other objects associated with it, and can be safely shared by multiple threads. To save memory space and optimize the performance of your program, you should reuse instances of immutable classes as much as possible , and avoid repeatedly creating instances of invariant classes with the same property values.

In the basic class library of JDK1.5, some immutable classes, such as the integer class, are optimized to have an instance cache that is used to store an integer instance that is used frequently in the program. The JDK1.5 integer class adds a static factory method valueOf (int i) with a parameter of type int, and its processing flow is as follows:

If (an instance with value I is present in the instance cache)

Return to this instance directly

else{

Create an I nteger instance with a value of I using the new statement

Store this instance in the instance cache

returns this instance

}

In the following program code, the integer example is obtained using the new statement and the valueOf (int i) method of the integer class, respectively :

I nteger a=new i nteger (10);

I nteger b=new i nteger (10);

I nteger c=i Nteger. valueOf (10);

I nteger d= i nteger. valueOf (10);

System.out.println (A==B); Print False

System.out.println (A==C); Print False

System.out.println (C==d); Print True

The above code creates a total of three Integer objects, see figure 11-4. A new Integer object is created by each new statement . The integer. ValueOf (10) method creates an integer object with a value of 10 only when it is first called , and obtains it directly from the instance cache when it is called the second time. Thus, in the program with the ValueOf () static factory method to obtain an integer object, you can improve the reusability of the integer object.


Immutable class with instance cache 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.