java immutability of String

  Yesterday the interview, the interviewer asked me immutability of String, I answered a little worse, and quickly check the information in order to sum up the memo!

First, the principle

  1, the same pattern (immutable)

  In parallel software development process, synchronous operation appears to be essential. When multiple threads read and write operations to the same object, in order to ensure the accuracy and consistency of the object data, it is necessary to synchronize an object. Synchronously operating the system performance loss is considerable. In order to remove these synchronous operation as much as possible, to improve the performance of parallel programs, you can use a non-subject change, relying on the object invariance, can still ensure that it remains an internal state in a multithreaded environment, there is no consistency in synchronous operation and correctness. This is the same pattern.

  The same model is inherently multi-threaded friendly, its core idea is that once an object is created, its internal state will never change. So, no one thread can modify its internal state and data, while its internal state and never will change on their own. Based on these characteristics, the object of constant multi-threaded operation does not require synchronization control.

  Also note, the same mode and read-only attributes are quite different, the same pattern is consistent and has more than reading invariance property. For the read-only attribute of the object, the object itself can not be modified by other threads, but the object itself but the state may amend its own example, the survival time of an object (object creation time and the time difference between the current time) is read-only, because no one third-party thread can not modify this property, but this property is a variable, because over time, the time when the survival of the Division are changing. The same pattern is required, for whatever reason, since the object is created, its internal state and data to maintain absolute stability.

  2, how to achieve immutable objects

  In the Java language, to achieve the same pattern is simple. After an object is created to ensure that any changes do not occur, and to ensure that the same work properly, just take note of the following four points:

    • Setter methods to remove and modify their properties all the way.
    • All property is set to private, and with a final mark, it can not be modified to ensure that
    • Make sure that no subclass can override modify its behavior.
    • There can create a complete object constructor.

And it is not the final function is very consistent. We review the role of java in the final.

    • final modification class that represents the class can not be inherited, commonly known as Duanzaijuesun class, all methods of the class automatically become final method
    • final modification method, a subclass can not override this method
    • final modification of the basic data types of variables, indicates that the variable is a constant, the value can not be modified
    • final modification reference type variable, indicating that the references can not point to other objects after the object is constructed, but the state of the referenced object points may vary

  It should be noted that: when modifying basic types of variables final, can not be re-assigned to the basic types of variables, basic types of variables can not be changed. But for purposes of reference type variable, which holds only a reference, final only guarantee that reference variables referenced address will not change, that has been a reference to the same object, but the object completely change can occur. For example, a final point to an array of references, it must point to a final point from the array initialization, but the contents of the array can be changed.

Two, String source code analysis

The following are some of the source jdk1.8 String class. 

public final class String implements java.io.Serializable, Comparable<String>, CharSequence {    
    
/** The value is used for character storage. */ private final char value[]; /** Cache the hash code for the string */
private int hash; // Default to 0 /** use serialVersionUID from JDK 1.0.2 for interoperability */ private static final long serialVersionUID = -6849794470754667710L; /**
...

  First of all you can see, the String class using the final modifier indicates that the String class can not be inherited. Then, we focus on member variables of the String class value, value is a char [] type, so the String object actually is packaged with this array of characters. Look at the value of the modifier, using private, did not provide setter methods, so you can not modify the external value of the String class, while also using the final value has been modified, can not be modified value within the String class, that is Once given value an initial value, value points to the address can not be changed. But the final modification of the above mentioned reference type variable content, we can only guarantee value can not point to another object, but the object pointed to state value can be changed. String class can be found by looking at the source code, the String class immutable, it is critical because SUN's engineer, in a method behind all of String's very careful not to touch the character in the array elements. So the key String class are immutable underlying implementation, rather than a final.

Third, modify the String it "variable"

  Although the final value is modified, simply stated value can not be redirected to other references. But the point value of the array can be changed under normal circumstances we have no way to access elements of the array pointed to this value. But, reflecting on the reflection can Niubi it. Attribute value can be reflected in a String object, thereby changing the structure of the array by changing the reference value obtained.

public static void main(String[] args) throws Exception {
    String str = "Hello World";
    System.out.println ( "pre-modification STR:" + STR);
    System.out.println ( "pre-modification of the memory address str" + the System.identityHashCode (str));
     // Get the value String class field 
    Field, ValueField = String. Class .getDeclaredField ( "value" );
     // change access attribute value 
    valueField.setAccessible ( to true );
     // get the value of the value attribute of the object str 
    char [] value = ( char []) valueField.get (str);
     // change the value array referenced characters 
    value [. 3] = '?' ;
    System.out.println ( "modified STR:" + STR);
    System.out.println ( "pre-modification of the memory address str" + the System.identityHashCode (str));
}

// operating results
 // you can see the string str sequence has been changed, but str memory addresses did not change. 
Str before the amendment: Hello World
str before modify memory addresses 1922154895
Str modified: Hel ? O World
str before modify memory addresses 1922154895

 Four, String designed as a cause of immutability

  In Java, the String designed as immutable is considered to memory, synchronizing result of various factors such as security and data structures, the following will do a summary of a variety of factors.

  1, runtime constant pool needs

  For example, the implementation of String s = "abc"; when this code is executed, JVM runtime constants first in the pool to see if there is a String object "abc", if the object already exists, do not create a new String object "abc", but s references directly to the runtime constant pool of existing String object "abc"; If the object does not exist, create a new String object "abc" at runtime constant pool, and then point to run often cited s the amount of the pool of the new String object is created.
So it will only create a runtime constant pool of a String object "abc", thus saving memory space.

    2, synchronous

  Because String objects are immutable, it is multi-threaded safe, with a String instance can be shared by multiple threads. This will not be used because of security thread synchronization.

  3, allowing the String object cache hashcode

  See above JDK1.8 String class source code can be found which has a hash field, String class guarantees the uniqueness of the immutability of hashcode, it may buffer hashcode String object with the hash field, each time there is no need to re- calculated hashcode. Therefore String object in Java is often used as a container such as a key HashMap.

  4, security

  If the String object is variable, it can cause serious security problems. For example, database user name and password are in the form of a string passed to obtain connection to the database, or in the socket programming, the host name and port are passed as a string. Because String objects are immutable, so its value can not be changed, otherwise hackers can drill loopholes, change the String object pointed reference value, resulting in vulnerabilities.

 

 

reference:

1、https://blog.csdn.net/dearKundy/article/details/82355019?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

2、https://blog.csdn.net/qq1404510094/article/details/80303334?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

 

Guess you like

Origin www.cnblogs.com/DDgougou/p/12588136.html