Why is a string in Java immutable? (Why String is immutable o ...

Source: Internet
Author: User

There is many reasons due to thestring classhas been made immutableinchJava. These reasonsinchView, concurrency issues, security issues and performance issues. Here isA list of various valid reasons to go forImmutablestring class: string is designed to be immutable in Java for a number of reasons. This is done primarily for concurrency issues, security issues, and performance issues. The following is a list of reasons for designing a string as immutable: synchronous1. The use of immutability isA best practice and have been recommended by many sources including effective Java and official Oracle Java tutorials. The property of theObject  isThat's none of the member variables thatObjectCan be changed asThey is marked as Privateand final. This property becomes an advantageinch  Caseof multi-threaded applications. Since the updating of the StringObject  isNot allowed, multiple threads cannot runinchTo synchronization issues which occur when oneObjectUpdates the state ofObject  whileThe other is reading theObject.1. "Using immutable Objects" is a best practice, and many places include effective Java (a book) and Oracle's official tutorials that recommend this guideline. All member variables of an immutable object are immutable because they are set to private and final. In a multithreaded environment, such attributes are a big advantage. Because modification of a string object is not allowed, there is no synchronization problem in a multithreaded environment, such as when a thread is updating data and another thread is reading the data. The official Oracle Java Tutorial says that developers should not has any doubt byusingImmutability. Usually developers think that by have immutability the number of objectsinchThe memory would increase because instead of updating anObjectANew ObjectHave to is created. ButinchReality This  isBalanced off by the reductioninchgarbage collector execution. If properly used immutability can make a application more stable. The official Oracle Tutorial says that developers should not have any qualms about using immutable objects. Developers often think that the number of immutable objects in memory is increasing because changes to an object do not actually modify the object, but instead produce new objects. ButinchReality This  isBalanced off by the reductioninchgarbage collector execution. The correct use of immutable objects in a program will make the application more stable. Performance2. The second reason whystring class  isImmutableinchJava isBoth a Cause asWell asEffect ofstringBeing immutable. StringsinchJavainchImplement the fly weight design pattern and the result is stringLiteral pool. This literal pool has theif stringLiteral isAlready presentinchThe literal pool then it'll be reused every-time astringReference variable isInitialized to astringliteral with the same characters.2The second reason that the string is immutable can also be understood as the result of a string immutable. In Java, strings are implemented in the "Enjoy meta" pattern, which leads to the advent of the string buffer pool, which is characterized by a string literal being reused every time a string reference is initialized with the same literal value as the one that is already in the buffer pool. The requirement forHaving astringLiteral pool arises fromThe fact thatstring class  isImmutableinchJava. Imagine a ScenariowhereMillions ofstringObjects has been created with same characters just because theNew operatorAlways creates and returns aNewInstance of theclassAnd we cannot modify astring ObjectOnce it has been created. The above scenario would resultinchPerformance issues. To avoid these performance issue,stringLiteral pool has been introducedinchjava. The creation of a string buffer pool is also based on the fact that string is immutable in Java. Suppose a scene: a hundreds of thousands of-meter string object with the same character is created, and this is simply because the new operator always creates and returns a fresh string instance, and every string created cannot be modified. This scenario will result in performance issues. To avoid these performance problems, Java introduces a string buffer pool. Now let us see whystringLiteral pool isA Cause forMakingstring classImmutableinchJava. Since thestringLiterals has to be reused, updating the contents of these objects should is not being allowed. had updating ofstringLiterals been allowed, astringliteral May is reused because its contents has been changed by another reference variable. Now let's see why the string buffer pool is also prompting the St The ring is designed to be an immutable cause. Since the string literal can be reused, the modification of the string is not allowed. If the modification of the string literal is allowed, then the string will no longer be reused because its contents have been modified by other reference variables. Performance3. The most used keyObject  forHash map isThestring Object. Every time astring  isReferencedinchHash based collections classes, it ' s hash code isCalculated. The hash code ofstringObjects depends upon the characters containedinchThatstring. If the characters of astring Objectwere allowed to being changed, the hash code of thatstring ObjectWhen the characters of thestringChange. By makingstring classImmutableinchJava, it has been insured that the hash code ofstring ObjectWon't change after thestring Objecthas been createdinchThe memory. More over, ThisAllows the hash code to be cached asA member variable. Once The hash code has been calculated forAstring Objectand isTold asThe value of This InternalMember variable, the same can be returned next time without the need forperforming any calculation.3The key value that is used most in the hash map is the string object. Each time a string is referenced by a collection class based on the hash algorithm, its hash value is computed. The result of the hash value depends on the individual characters contained in the string. If the characters in the string can be changed, then the hash value of the string will change as the character changes. By designing the string as immutable, it is guaranteed that the hash value of the string will not change when it is created in memory. This allows the hash value to be cached as a member variable, and once the hash value of a string object is computed and used as the internal variable of the string, the next time you need to use the hash value, you can return the same value without additional calculations. Safety4. The security aspect of having thestring classImmutableinchJava isThat strings is used forFile operations, memory management and network operations. If strings is allowed to being mutable, various properties could be changedinchmalicious ways.4The reason the string is designed to be immutable in terms of security is that string is used for file manipulation, memory management, and network operations. If the string can be modified, many of the properties will potentially be modified maliciously. Simple5. Another reason to make thestring classmutable isThe simplicity aspect. Though forBeginners it isA learning curve to understand the behavior ofstringObjects but once they understand, it isVery easy to visualize the behavior ofstringObjectsinchAny particular scenario. Allowing the updating ofstringobjects would has made it more complex to understand the behavior of strings.5another reason to design a string as immutable is for simple reasons. Although it is more difficult for beginners to understand the behavior of string objects, it is easy to understand the behavior of string objects in any particular scenario once they understand it. and the design of strings to be mutable will make this process of understanding more complicated. the point to note about the design decision isThat the advantages of makingstring classimmutable is more than not making it immutable. Note: The reason for this design is that the string is more advantageous than variable string. 

======== Personal Summary =========

The reason string is designed to be immutable is determined by the role of string.

1. This resolves the synchronization security issue.

2. The design is immutable, resulting in performance degradation, since each modification will result in a new object, and the string buffer pool is a good solution to this problem.

3. Security, because a lot of operations are strings as parameters, if the string can be modified, then in the course of our operation if someone has modified the string, then we will not get the correct result.

Resources:

(1) Http://www.java experience.com/why-the-string-class-is-immutable/#ixzz2grdKUGIh

(2) http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html

Why is a string in Java immutable? (Why String is immutable o ...

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.