The introduction
Went to the interview on Friday and was dumb again with a question from the interview
Interviewer: What’s the difference between StringBuilder and StringBuffer? Interviewer: So what is it about StringBuilder that makes it unsafe? Me:… (Mute)
StringBuilder is not thread-safe. StringBuffer is thread-safe. Why StringBuilder is not thread-safe has never occurred to me.
Analysis of the
Before we get into the setup, we need to know that the internal implementation of StringBuilder and StringBuffer, like String, stores strings ina char array, except that the char array in String is final and immutable. The char arrays of StringBuilder and StringBuffer are mutable.
Let’s start with a little code to see what happens when you manipulate a StringBuilder object with multiple threads
public class StringBuilderDemo {
public static void main(String[] args) throws InterruptedException {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 10; i++){
new Thread(new Runnable() {
@Override
public void run(a) {
for (int j = 0; j < 1000; j++){
stringBuilder.append("a");
}
}
}).start();
}
Thread.sleep(100); System.out.println(stringBuilder.length()); }}Copy the code
We can see that this code creates 10 threads, each looped 1000 times into the StringBuilder object for the Append character. Normally the code should output 10000, but what does the actual run output?
We see the output of the “9326”, 10000 less than expected, and it also throws a ArrayIndexOutOfBoundsException anomalies (abnormal not will now).
1. Why is the output value different from the expected value
Let’s take a look at two member variables of StringBuilder that are actually defined in AbstractStringBuilder. Both StringBuilder and StringBuffer inherit AbstractStringBuilder.
// Store the contents of the string
char[] value;
// The number of character arrays already in use
int count;
Copy the code
Look again at the StringBuilder append() method:
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
Copy the code
AbstractStringBuilder’s append() method calls AbstractStringBuilder’s append() method
1.public AbstractStringBuilder append(String str) {
2. if (str == null)
3. return appendNull();
4. int len = str.length();
5. ensureCapacityInternal(count + len);
6. str.getChars(0, len, value, count);
7. count += len;
8. return this;
9.}
Copy the code
Regardless of what’s going on in line 5 and 6, let’s look at line 7. Count += len is not an atomic operation. Let’s say that count is 10, len is 1, and both threads go to line 7, and they both get count 10, and then they add and assign the result to count, so they get count 11 instead of 12. This is why the test code outputs a value less than 10000.
2, why sell ArrayIndexOutOfBoundsException anomalies.
AbstractStringBuilder append(), ensureCapacityInternal() checks whether the char array of a StringBuilder object can hold a new string. Call expandCapacity() to expand the char array.
private void ensureCapacityInternal(int minimumCapacity) {
// overflow-conscious code
if (minimumCapacity - value.length > 0)
expandCapacity(minimumCapacity);
}
Copy the code
The expansion logic is to create a new char array with twice the size of the original char array plus 2, copy the contents of the original char array to the new array using system.arrycopy (), and finally point to the new char array.
void expandCapacity(int minimumCapacity) {
// Calculate the new capacity
int newCapacity = value.length * 2 + 2;
// Some checking logic is omitted. value = Arrays.copyOf(value, newCapacity); }Copy the code
Arrys. CopyOf () method
public static char[] copyOf(char[] original, int newLength) {
char[] copy = new char[newLength];
// Copy the array
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
Copy the code
AbstractStringBuilder append(); AbstractStringBuilder append();
str.getChars(0, len, value, count);
Copy the code
GetChars () method
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
// Some checks are omitted. System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin); }Copy the code
See the following figure for the copy process
Thread 1 STR., continue to implement the sixth line getChars () method to get the count value is 6, enforce char array copy will be thrown ArrayIndexOutOfBoundsException anomalies.
At this point, the analysis of why StringBuilder is unsafe is done. What if we replaced the StringBuilder object of our test code with a StringBuffer object?
So what does StringBuffer do to make it thread-safe? You can see this in the append() method of StringBuffer.