Why the string class in Java is designed to be final

Source: Internet
Author: User
Tags readable

A few days ago the interview encountered a very difficult question about string, "Why is the string designed to be immutable"? A similar question is "why is a string designed to be final?" "Personally think that the previous approach is more accurate, designed to final only guarantee that the string class can not be inherited, and immutable is more stringent than final."

The following are mainly translated from: http://java67.blogspot.sg/2014/01/why-string-class-has-made-immutable-or-final-java.html

to answer this question, Java programmers must have a deep understanding of how string works, what its characteristics are, and some key principles. The string class is a God class in Java, and it has features that other classes do not have, such as string literals stored in a constant pool, and you can concatenate multiple strings with the operator "+". Given the importance of the string class in Java programming, the Java designer has designed it to be final, which means that you cannot inherit the class, which also helps the string object to be immutable.  Remember reading somewhere, someone asked the creator of Java James Gosling Why the String class was designed to be final, but he made some answers on security. Some argue that making a class final severely limits its ability to evolve or expand, and James commented that designing a class as final is a key factor in the Java security promise so that no one in the Java platform can change its behavior.  now back to the title question, why is string in Java immutable? The first thing to be sure is that this design has an advantage. Now, let's think about these advantages or features, which is why we decided to design this.
 Here are 5 reasons why a string is designed as final or immutable in Java:In addition to Jamesgosling's tips on security, I think the following reasons also explain why a string is designed in Java as final or immutable 1) string constant poolJava designers understand that the string class will be the most used class in all Java applications, which is why they want to optimize from the beginning of the design. A key idea of the optimization direction is to store string literals in a string constant pool. The goal is to reduce the temporary string object by sharing, and for sharing, the string class must be immutable. You cannot share mutable objects between two parties that are not mutually aware of each other. Let's take a hypothetical example where two of the reference variables point to the same string object:String S1 = "Java";String s2 = "Java";now, if the value of S1 is changed to "C + +", the reference variable s2 his value into "C + +" without knowing it. However, by designing the string as immutable, the shared string literal above becomes possible. In short, to implement the key idea of string pooling in Java, the string class must be designed to be immutable.  2) SecurityJava has a clear goal in providing a secure environment for every level of service, and strings are critical throughout the security aspect. String has been widely used as a parameter for many Java classes, for example, when opening a network connection, you can pass a host and port as a string, while reading a file in Java, you can pass the path of the file and directory as a string, and when you open a database connection, you can pass the database URL as a string. If the string is not immutable, the user may have authorized access to a specific file on the system, but after authentication, he can change the path to another file, which can cause serious security problems. Similarly, variable string values can pose a security threat when connecting to any other machine in the database or network. Mutable strings can also cause security problems in reflection, because parameters are strings.  3) Application of string in class loading mechanismanother reason for making a string final or immutable is because it is heavily used in the class loading mechanism. Because the string is not immutable, an attacker could take advantage of this fact to change the request to load a standard Java class (for example, Java.io.Reader) to a malicious class com.un unknown n.datastolenreader. By keeping the string final and immutable, we can at least ensure that the JVM is loading the correct class.  4) Multithreading Benefitsbecause concurrency and multithreading are key products of Java, it makes sense to consider thread security for string objects. Because expected strings will be widely used, making them immutable means there is no additional synchronization, which means that the code to share strings between multiple threads is much simpler. This single feature makes it easier to have complex, chaotic, and error-prone concurrent encodings. Because the string is immutable, and we only share it between threads, it produces more readable code. 5) Optimization and performancenow, when you make the class immutable, you know beforehand that the class will not change once it is created. This ensures that many of the performance optimizations are open-minded, such as caching. The string itself knows that I will not change, so the string caches its hashcode. It even delays computing hashcode, once created, just cache it. In a simple world, when you first call any of the hashcode () methods of any string object, it computes the hash code, and then all subsequent calls to Hashcode () return the cached values that have been computed. This will result in good performance gains, as strings are used extensively in hash-based mappings such as Hashtable and HashMap. If you do not make it immutable, you cannot cache the hash code, because it depends on the contents of the string itself.    In addition to these advantages, you can also consider the advantages of the string being immutable in Java. It is one of the most popular objects that can be used as keys based on hash collections, such as HashMap and Hashtable. Although immutability is not absolutely required for hashmap keys, it is much safer to use an immutable object as a key than to use a mutable object, because if the Mutable object's state is changed during HashMap, it is not possible to retrieve it because its eques () The and Hashcode () methods depend on the property that has changed. If a class is immutable, then when it is stored in a hash-based collection, there is no risk of changing its state, and another important benefit I have highlighted is its thread safety. Because strings are immutable, you can safely share them between threads without worrying about additional synchronizations. It makes concurrent code more readable and reduces the occurrence of errors.   Despite all these advantages, immutability has some drawbacks, for example, it is not without cost. Because the string is immutable, it generates a large number of temporary objects and escape objects, which can put pressure on the garbage collector. Java designers have considered that storing string literals in a constant pool is a solution to their reduction in string garbage. This is really helpful, but you must be careful to create strings without using constructors, for example, new string () does not select objects from the string pool. And, on average, Java applications produce too much garbage. In addition, storing strings in the pool has a hidden risk associated with them. The string pool is in the PermGen space of Javaheap, which is very limited compared to javaheap. Having too many string literals will quickly fill this space, leading to java.lang.OutOfMemoryError. Fortunately, the Java language Designer is aware of this problem, starting with Java 7, they move the string pool to the normal heap space, which is much larger than the PermGen space. There is another drawback to making a string immutable because it restricts its extensibility. Now, you cannot extend the string to provide more functionality, although it is rarely required.    

Why the string class in Java is designed to be final

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.