JAVA immutable class (the immutable) String mechanism of immutability

I. Introduction immutable class

Immutable classes : the so-called immutable class refers to the instance of the class, once created, can not change the variable values of its members. The JDK comes inside many immutable class: Interger, Long and String.
Variable categories : with respect to the immutable class, create an instance variable class member variables may change its value, most of the development to create classes belong to the class variable.

Second, the advantage of an immutable class

Then the difference between variable and immutable class of class, we need to understand why there must be immutable class? Such characteristics of what kind of benefits for JAVA?

  1. Thread-safe
    immutable objects are thread-safe and can be shared between threads in each other, without the use of special mechanisms to ensure synchronization problem, because the value of the object can not be changed. Can reduce the possibility of concurrency errors, since no use some locking mechanism ensures memory coherency problem also reduce synchronization overhead.
  2. Easy to construct, use and testing
  3. ...

Third, the design method of an immutable class

For the design immutable classes, personal summed up the following principles:

1. Add final modifier class, to ensure that the class is not inherited .
If the class can be inherited immutability mechanism would undermine the class, as long as the parent class inherited class coverage and inherited class members can change the variable value, then once in the form of a subclass of parent class can not guarantee whether the current class variable.

2. ensure that all member variables must be private, and add final modified
in this way to ensure that member variables can not be changed. But only do this step is not enough, because if the object is a member variable with the possibility of external change its value. So the first 4:00 to make up for this deficiency.

3. The method does not provide changing member variables, including setter
avoided by other interface changes the value of a member variable, damage immutable characteristic.

4. A member through all initialized, deep copy (deep copy)

If passed in the constructor object directly assigned to the member variables, you can still modify the incoming object which led to changes in the value of internal variables. E.g:

public final class ImmutableDemo {  
    private final int[] myArray;  
    public ImmutableDemo(int[] array) {  
        this.myArray = array; // wrong  
    }  
}

In this manner can not be guaranteed immutability, myArray point to the same array, and a memory address, a user can change the value of the internal myArray array by modifying the value of an object outside ImmutableDemo.
In order to ensure the internal value is not modified, copy depth can be used to create a new memory to hold the value passed. The right approach:

public final class MyImmutableDemo {  
    private final int[] myArray;  
    public MyImmutableDemo(int[] array) {  
        this.myArray = array.clone();   
    }   
}

5. getter process, do not directly return the object itself, but the clone object and returns a copy of the object
of this approach is to prevent leakage of the object, the object member variable is obtained to prevent the getter direct operation via internal member variables causing the members variable is changed.

Fourth, the immutability of String objects

after a string object in memory to create immutable, create more than meet the five general principles of immutable objects, we see how the String codes are 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 first index of the storage that 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操作
     }
    ...
     public char[] toCharArray() {
     // Cannot use Arrays.copyOf because of class initialization order issues
        char result[] = new char[value.length];
        System.arraycopy(value, 0, result, 0, value.length);
        return result;
    }
    ...
}

As shown in the code, the following design details can be observed:

  1. String class is final modification, can not be inherited
  2. All members of the internal string variables are set to private
  3. value of the setter does not exist
  4. And the value and offset settings as final.
  5. When an incoming variable array value [], rather than directly for copy value [] copied to internal variables.
  6. Not directly returned object reference acquisition value, but the return copy of the object.

This is in line with the same type of characteristics summarized above, also ensures that a String is immutable class.

Fifth, the immutability of the advantages and disadvantages of the String object

From an analysis, String data is immutable classes that provide such features what good is it? I summarized as follows:

1. String require constant pool .
String constant pool can be some of the character constants in the constant pool reused to avoid re-created each time the same object, to save storage space. But if the string is variable, this time also point to the same content String constant pool of the same memory space, when a variable changes the value of the memory, the other of traversal value changes also occur. So do not meet the constant pool design in mind.

2. Thread safety considerations .
Examples of the same string can be shared by multiple threads. This will not be used because of security thread synchronization. String own is thread-safe.

3. The class loader to use strings, immutable security is provided, so that the correct classes are loaded . For example, you want to load java.sql.Connection class, and this value is changed myhacked.Connection, it will cause damage to your database agnostic.

4. Support hash mapping and caching.
Because strings are immutable, so when it was created hashcode cached, do not need to be recalculated. This makes it suitable as a string of keys in the Map, the processing speed of the string to be faster than the other key objects. This is often the key in HashMap string.

Disadvantages:

  1. If there is a demand for change in the value of the String object, it will create a large number of String objects.

Sixth, the really immutable String object

Although the String object value is set to final, and also through a variety of mechanisms to ensure that its member variables can not be changed. But it can still change its value by means of reflection. E.g:

    //创建字符串"Hello World", 并赋给引用s
    String s = "Hello World"; 
    System.out.println("s = " + s); //Hello World

    //获取String类中的value字段
    Field valueFieldOfString = String.class.getDeclaredField("value");
    //改变value属性的访问权限
    valueFieldOfString.setAccessible(true);

    //获取s对象上的value属性的值
    char[] value = (char[]) valueFieldOfString.get(s);
    //改变value所引用的数组中的第5个字符
    value[5] = '_';
    System.out.println("s = " + s);  //Hello_World

Print results:

s = Hello World
s = Hello_World

Found String has changed. That is, the reflector can be modified by a so-called "immutable" object

to sum up

Is immutable class instance creation can not be changed after the value of the member traversal. This feature allows an immutable class provides thread-safe features, but also brings the cost of object creation, each change a property is to re-create a new object. JDK also provides many internal immutable class such as Integer, Double, String, etc. String immutable characteristic mainly to meet the constant pool, thread-safe, the class loader needs. The rational use of immutable class can bring great benefits.

Reference material

[1] http://my.oschina.net/zzw922cn/blog/487610

[2] java's String Why are immutable: http://www.codeceo.com/article/why-java-string-immutable.html

[3] http://www.importnew.com/7535.html

Original Address: https: //www.cnblogs.com/jaylon/p/5721571.html

I. Introduction immutable class

Immutable classes : the so-called immutable class refers to the instance of the class, once created, can not change the variable values of its members. The JDK comes inside many immutable class: Interger, Long and String.
Variable categories : with respect to the immutable class, create an instance variable class member variables may change its value, most of the development to create classes belong to the class variable.

Second, the advantage of an immutable class

Then the difference between variable and immutable class of class, we need to understand why there must be immutable class? Such characteristics of what kind of benefits for JAVA?

  1. Thread-safe
    immutable objects are thread-safe and can be shared between threads in each other, without the use of special mechanisms to ensure synchronization problem, because the value of the object can not be changed. Can reduce the possibility of concurrency errors, since no use some locking mechanism ensures memory coherency problem also reduce synchronization overhead.
  2. Easy to construct, use and testing
  3. ...

Third, the design method of an immutable class

For the design immutable classes, personal summed up the following principles:

1. Add final modifier class, to ensure that the class is not inherited .
If the class can be inherited immutability mechanism would undermine the class, as long as the parent class inherited class coverage and inherited class members can change the variable value, then once in the form of a subclass of parent class can not guarantee whether the current class variable.

2. ensure that all member variables must be private, and add final modified
in this way to ensure that member variables can not be changed. But only do this step is not enough, because if the object is a member variable with the possibility of external change its value. So the first 4:00 to make up for this deficiency.

3. The method does not provide changing member variables, including setter
avoided by other interface changes the value of a member variable, damage immutable characteristic.

4. A member through all initialized, deep copy (deep copy)

If passed in the constructor object directly assigned to the member variables, you can still modify the incoming object which led to changes in the value of internal variables. E.g:

public final class ImmutableDemo {  
    private final int[] myArray;  
    public ImmutableDemo(int[] array) {  
        this.myArray = array; // wrong  
    }  
}

In this manner can not be guaranteed immutability, myArray point to the same array, and a memory address, a user can change the value of the internal myArray array by modifying the value of an object outside ImmutableDemo.
In order to ensure the internal value is not modified, copy depth can be used to create a new memory to hold the value passed. The right approach:

public final class MyImmutableDemo {  
    private final int[] myArray;  
    public MyImmutableDemo(int[] array) {  
        this.myArray = array.clone();   
    }   
}

5. getter process, do not directly return the object itself, but the clone object and returns a copy of the object
of this approach is to prevent leakage of the object, the object member variable is obtained to prevent the getter direct operation via internal member variables causing the members variable is changed.

Fourth, the immutability of String objects

after a string object in memory to create immutable, create more than meet the five general principles of immutable objects, we see how the String codes are 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 first index of the storage that 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操作
     }
    ...
     public char[] toCharArray() {
     // Cannot use Arrays.copyOf because of class initialization order issues
        char result[] = new char[value.length];
        System.arraycopy(value, 0, result, 0, value.length);
        return result;
    }
    ...
}

As shown in the code, the following design details can be observed:

  1. String class is final modification, can not be inherited
  2. All members of the internal string variables are set to private
  3. value of the setter does not exist
  4. And the value and offset settings as final.
  5. When an incoming variable array value [], rather than directly for copy value [] copied to internal variables.
  6. Not directly returned object reference acquisition value, but the return copy of the object.

This is in line with the same type of characteristics summarized above, also ensures that a String is immutable class.

Fifth, the immutability of the advantages and disadvantages of the String object

From an analysis, String data is immutable classes that provide such features what good is it? I summarized as follows:

1. String require constant pool .
String constant pool can be some of the character constants in the constant pool reused to avoid re-created each time the same object, to save storage space. But if the string is variable, this time also point to the same content String constant pool of the same memory space, when a variable changes the value of the memory, the other of traversal value changes also occur. So do not meet the constant pool design in mind.

2. Thread safety considerations .
Examples of the same string can be shared by multiple threads. This will not be used because of security thread synchronization. String own is thread-safe.

3. The class loader to use strings, immutable security is provided, so that the correct classes are loaded . For example, you want to load java.sql.Connection class, and this value is changed myhacked.Connection, it will cause damage to your database agnostic.

4. Support hash mapping and caching.
Because strings are immutable, so when it was created hashcode cached, do not need to be recalculated. This makes it suitable as a string of keys in the Map, the processing speed of the string to be faster than the other key objects. This is often the key in HashMap string.

Disadvantages:

  1. If there is a demand for change in the value of the String object, it will create a large number of String objects.

Sixth, the really immutable String object

Although the String object value is set to final, and also through a variety of mechanisms to ensure that its member variables can not be changed. But it can still change its value by means of reflection. E.g:

    //创建字符串"Hello World", 并赋给引用s
    String s = "Hello World"; 
    System.out.println("s = " + s); //Hello World

    //获取String类中的value字段
    Field valueFieldOfString = String.class.getDeclaredField("value");
    //改变value属性的访问权限
    valueFieldOfString.setAccessible(true);

    //获取s对象上的value属性的值
    char[] value = (char[]) valueFieldOfString.get(s);
    //改变value所引用的数组中的第5个字符
    value[5] = '_';
    System.out.println("s = " + s);  //Hello_World

Print results:

s = Hello World
s = Hello_World

Found String has changed. That is, the reflector can be modified by a so-called "immutable" object

to sum up

Is immutable class instance creation can not be changed after the value of the member traversal. This feature allows an immutable class provides thread-safe features, but also brings the cost of object creation, each change a property is to re-create a new object. JDK also provides many internal immutable class such as Integer, Double, String, etc. String immutable characteristic mainly to meet the constant pool, thread-safe, the class loader needs. The rational use of immutable class can bring great benefits.

Reference material

[1] http://my.oschina.net/zzw922cn/blog/487610

[2] java's String Why are immutable: http://www.codeceo.com/article/why-java-string-immutable.html

[3] http://www.importnew.com/7535.html

Original Address: https: //www.cnblogs.com/jaylon/p/5721571.html

Guess you like

Origin www.cnblogs.com/jpfss/p/11527127.html