the difference between the String,stringbuffer,stringbuilder
Three differences of classes
From the source code of three classes, we can see that the three storage strings are stored in the character char[]
String class source code:
StringBuffer and StringBuilder's parent class source code:
The array of string is decorated with the final modifier, visible is not modifiable, while the StringBuffer and StringBuilder source code provides a large number of practical operation strings, the string additions and deletions are very convenient. Thread is safe
Let's talk about what you call thread safety.
Thread-Safe is multithreaded access, with the lock mechanism, when a thread accesses the data of the class, protection, other threads can not access until the thread read, other threads to use. There is no data inconsistency or data contamination.
Thread is not secure is not provide data access protection, it is possible to have multiple threads change the data caused by the data is dirty data
As mentioned above, string is immutable, can be understood as constant, is safe (the source code also added a synchronous lock), there is no discussion.
StringBuffer Source:
StringBuilder Source:
In contrast, the StringBuffer method has been synchronized with the Synchronized keyword before, ensuring that there is only one way to execute the method at the same point in time. While StringBuilder does not guarantee synchronization, StringBuffer is thread-safe and StringBuilder is not thread-safe. performance analysis of the three
Here we first refer to an actual test diagram (reference)
This is the test of the three cases in string concatenation
It is clear that string is not suitable for defining strings that are often modified, StringBuilder and StringBuffer are only minor differences, and the individual believes that, primarily because of the synchronized keyword, the JVM needs to determine whether there is a process conflict (personal opinion).
In summary, if the string does not need to be modified frequently, it is sufficient to use a string. If the string needs to change according to the requirements at any time, single-threaded case can be implemented with StringBuilder, multithreading or use StringBuffer bar.