Immutable class Cache

Source: Internet
Author: User

The status of an instance of an unchangeable class does not change. Such an instance can be securely shared by other associated objects and securely shared by multiple threads. To save memory space and optimize program performance, you should try to reuse instances of immutable classes to avoid repeated creation of immutable classes with the same attribute value.

In the basic class library of JDK 1.5, some immutable classes, such as integer classes, are optimized. They have an instance cache to store integer instances that are frequently used in programs. The integer class of JDK 1.5 adds a parameter valueof (int I) for the static factory method of the int type. The processing process is as follows:

If (an instance with a value of I exists in the instance cache)
Directly return this instance
Else {
Use the new statement to create an integer instance with the value of I
Store this instance in the instance Cache
Return this instance
}

In the following program code, use the new statement and the valueof (int I) method of the integer class to obtain the integer instance.

Integer A = new INTEGER (10 );
Integer B = new INTEGER (10 );

Integer c = integer. valueof (10 );
Integer d = integer. valueof (10 );

System. Out. println (A = B); // print false
System. Out. println (A = C); // print false

System. Out. println (C = D); // print true

The preceding Code creates three integer objects. Each new statement creates a new integer object. The integer. valueof (10) method only creates an integer object with a value of 10 when it is called for the first time. When it is called for the second time, it is obtained directly from the instance cache. It can be seen that using the valueof () Static factory method in the program to obtain integer objects can improve the reusability of integer objects.

How does one implement instance caching? There is no fixed Implementation Method for caching. The perfect cache implementation should not only consider when to add the instance to the cache, but also consider when to promptly clear the instances that are no longer in use from the cache, to ensure effective and reasonable use of memory space. A simple implementation is to directly use Java collections as instance cache.

The following routine has the instance cache and the corresponding static factory method valueof (). A large number of name objects may be added to the instance cache of the name class. To prevent memory depletion, softreference is stored in the instance cache ). If an object only holds soft references, the Java Virtual Machine recycles its memory when the memory is insufficient.

Routine 11-12 name. Java

Import java. util. Set;
Import java. util. hashset;
Import java. util. iterator;
Import java. Lang. Ref .*;

Public class name {
...
// Instance cache, which stores soft references to name objects

Private Static final set <softreference <Name> names = new hashset <softreference <Name> ();

Public static name valueof (string firstname, string lastname) {// static factory Method

Iterator <softreference <Name> it = names. iterator ();

While (it. hasnext ()){
Softreference <Name> ref = it. Next (); // obtain soft reference
Name = ref. Get (); // obtain the name object referenced by the soft reference
If (name! = NULL & name. firstname. Equals (firstname) & name. lastname. Equals (lastname ))
Return name;
}

// If the name object does not exist in the cache, create the object and add its soft reference to the instance cache.

Name = new name (firstname, lastname );
Names. Add (New softreference <Name> (name ));
Return name;

}

Public static void main (string ARGs []) {

Name n1 = Name. valueof ("Xiaohong", "Wang ");
Name n2 = Name. valueof ("Xiaohong", "Wang ");
Name N3 = Name. valueof ("Xiao Dong", "Zhang ");
System. Out. println (N1 );
System. Out. println (N2 );
System. Out. println (N3 );
System. Out. println (n1 = n2); // print true
}

}

In a program, you can use the new statement to create a name instance or the valueof () method to create a name instance. In the life cycle of a program, you should use the new statement to create a name instance that does not need to be frequently accessed by the program so that it can end the life cycle in time; for the name instance that the program needs to access frequently, use the valueof () method to obtain it, because this method can put the name instance in the cache so that it can be reused.

Tips

From the name class of the routine 11-12, we can also see that in some cases, a class can provide both public constructor and static factory methods. You can flexibly decide how to obtain the class instance based on your actual needs.

In addition, it is not necessary to provide instance cache for all immutable classes. Creating a large number of instance caches at will results in a waste of memory space and reduces program running performance. Generally, the instance cache is required only for non-variable classes that meet the following conditions.

1. The number of instances of the unchangeable class is limited.
2. During the program running, you need to frequently access certain instances of immutable classes. These instances have the same long life cycle as the program itself.

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.