Java immutable Class (immutable) mechanism and string immutability (recommended) _java

Source: Internet
Author: User
Tags arrays reflection

Introduction of Immutable Class

Immutable class: The so-called immutable class means that once the instance of this class has been created, it cannot change its member variable values. Many immutable classes, such as Interger, long, and string, are brought in from within the JDK.
mutable classes: In contrast to immutable classes, a mutable class can change its member variable values after an instance is created, and most of the classes created in development belong to the Mutable class.

Second, the advantages of immutable classes

After saying the difference between mutable classes and immutable classes, we need to learn more about why immutable classes are required. What are the benefits of this feature for Java?

1. Thread Safety

Immutable objects are thread-safe, they can be shared between threads, and there is no need to use special mechanisms to guarantee synchronization problems because the values of objects cannot be changed. Can reduce the likelihood of concurrent errors, because there is no need to use some locking mechanisms to ensure memory consistency problems also reduce the synchronization overhead.

2. Easy to construct, use and test

3...

The design method of immutable class

For the design of immutable classes, individuals have summed up the following principles:

1. Class adds final modifier to ensure that the class is not inherited.

If a class can be inherited that destroys the invariant mechanism of a class, as long as the inheriting class overrides the parent's method and the inheriting class can change the member variable value, the current class is not guaranteed to be mutable once the subclass appears as a parent class.

2. Ensure that all member variables must be private, plus final modification

In this way, the member variable is guaranteed to be immutable. But it's not enough to do that, because it's possible for an object member variable to change its value externally. So the 4th remedy for this deficiency.

3. Does not provide a way to change member variables, including setter

Avoid changing the value of member variables through other interfaces and destroying immutable properties.

4. Initialize all members through the constructor for deep copy (deep copy)

If the object passed in by the constructor is assigned directly to a member variable, it is possible to change the value of the internal variable by modifying the incoming object. For example:

Public final class Immutabledemo { 
private final int[] myarray; 
Public Immutabledemo (int[] array) { 
This.myarray = array;//Wrong 
} 
}

This method does not guarantee immutability, myarray and array point to the same memory address, the user can change the value of the array object outside the Immutabledemo by modifying the value of the myarray inside.

To ensure that the internal values are not modified, you can use depth copy to create a new memory to save the incoming values. Correct procedure:

Public final class Myimmutabledemo { 
private final int[] myarray; 
Public Myimmutabledemo (int[] array) { 
This.myarray = Array.clone (); 
} 
}

5. In the getter method, do not return directly to the object itself, but rather to clone the object and return the copy of the object

This approach is also to prevent the object from leaking out, to prevent the use of getter after the internal variable member objects directly to the member variables, resulting in changes in member variables.

Non-variability of string objects

The string object cannot be changed after memory is created, and the creation of immutable objects generally satisfies the above 5 principles, and we look at how the string code is implemented.

Public final class String
implements Java.io.Serializable, Comparable<string>, charsequence
{
/** The value is used for character storage. *
Private final char value[];
/** the ' offset is ' the ' storage ' is used. * *
private final int offset;
/** The count is the number of characters in the String. *
private final int count;
/** Cache The hash code for the string */
private int hash;//Default to 0
....
Public String (char value[]) {
this.value = arrays.copyof (value, value.length);//Deep copy Operation
}
... Public
char[] ToCharArray () {
//cannot use arrays.copyof because of class initialization order issues
Cha R Result[] = new Char[value.length];
System.arraycopy (value, 0, result, 0, value.length);
return result;
}
...

As shown in the code above, you can observe the following design details:

The 1.String class is final decorated and cannot be inherited

2.string internal all members are set to private variables

3. Setters that do not exist value

4. and set the value and offset to final.

5. When passing in a variable array value[], copy instead of directly value[to the internal variable.

6. Instead of returning the object reference directly, get value returns copy of the object.

This is consistent with the invariant type characteristics summarized above, and also guarantees that the string type is an immutable class.

The advantages and disadvantages of the immutability of String objects

From the previous section, string data immutable classes, what is the benefit of setting such an attribute? I summarize the following points:

1. String constant pool needs.

A string constant pool can be reused in a constant pool with some character constants to avoid recreating the same object each time, saving storage space. However, if the string is mutable, the same content string also points to the same memory space of the constant pool, and when a variable changes the value of that memory, other traversal values change. So it does not conform to the original intent of the constant pool design.

2. Thread safety considerations.

The same string instance can be shared by multiple threads. This will not use synchronization because of thread-safety issues. The string itself is thread-safe.

3. The class loader uses a string, and immutability provides security so that the correct class is loaded. For example, if you want to load the Java.sql.Connection class, and this value is changed to myhacked.connection, it will cause an unknown damage to your database.

4. Support hash mapping and caching.

Because the string is immutable, the hashcode is cached when it is created and does not need to be recalculated. This makes the string suitable for the key in the map, and the string is processed faster than the other key objects. This is where the keys in HashMap tend to use strings.

Disadvantages:

1. If there is a need to change the value of a string object, a large number of string objects are created.

Whether the string object is really immutable

Although the string object sets value to final, it also ensures that its member variables are immutable through a variety of mechanisms. However, the value can be changed by means of reflection mechanism. For example:

Creates the string "Hello World" and assigns it to the reference s
string s = "Hello World"; 
System.out.println ("s =" + s); Hello World
//Get the Value field in the String class
field valuefieldofstring = String.class.getDeclaredField ("value")
; Change the access rights of the Value property
valuefieldofstring.setaccessible (true);
Gets the value of the values property on the S object
char[] value = (char[]) valuefieldofstring.get (s);
Change the 5th character in the array referenced by value
value[5] = ' _ ';

Printing results are:

s = Hello World

The value of the string was found to have changed. That is, by reflection, you can modify what is called an "immutable" object.

Summarize

Immutable classes are values that cannot be changed by member traversal after an instance is created. This feature enables the immutable class to provide thread-safe attributes but also brings the cost of object creation, each of which changes a property to recreate a new object. The JDK also provides a number of immutable classes such as integers, Double, string, and so on. The immutable nature of a string is intended primarily to satisfy the requirements of constant pooling, thread safety, and class loading. The rational use of immutable classes can bring great benefits.

The above is a small set to introduce the Java immutable Class (immutable) mechanism and string invariance (recommended), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.