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