Stringbuilder 和Stringbuffer 的区别

原文链接:https://blog.csdn.net/Farrell_zeng/article/details/100153345

StringBuilder和StringBuffer的区别在哪里?
当接触这个问题的时候,我们可能第一反应就是,StringBuilder是线程不安全的,StringBuffer是线程安全的

为什么StringBuilder是线程不安全,StringBuffer是线程安全?
针对这个问题,大部分的人可能就无言以对了,我们只知道StringBuilder是线程不安全的,StringBuffer是线程安全的,却不知道为什么,所谓知其然,而不知其所以然,针对这个问题,做一次分享

分析
在分析这个问题之前,我们要知道StringBuilder和StringBuffer的内部实现其实跟String是一样的,都是通过一个char类型的数组进行存储字符串的,不同的是String类中的char数组是final修饰的,是不可变的,而StringBuilder和StringBuffer中的char数组没有被final修饰,是可变的。

public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
/** The value is used for character storage. */
private final char value[];
......
}
String类源码line4, 我们可以看到,char数组是被final修饰的

abstract class AbstractStringBuilder implements Appendable, CharSequence {
/**
* The value is used for character storage.
*/
char[] value;

/**
* The count is the number of characters used.
*/
int count;
 
......
}

StringBuilder和StringBuffer都继承了AbstractStringBuilder,在line5, char类型数组没有被final修饰

首先我们先做一个测试用例,如下:

import org.junit.Test;
public class StringBuilderTest {

@Test
public void test() throws InterruptedException {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 100; i++) {
new Thread(() -> {
for (int j = 0; j < 1000; j++) {
stringBuilder.append("a");
}
}).start();
}

Thread.sleep(500L);
System.out.println(stringBuilder.length());
}
}


输出结果如下:

Exception in thread "Thread-84" java.lang.ArrayIndexOutOfBoundsException
at java.lang.String.getChars(String.java:826)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:449)
at java.lang.StringBuilder.append(StringBuilder.java:136)
at test.wby.dingtalk.StringBuilderTest.lambda$test$0(StringBuilderTest.java:19)
at java.lang.Thread.run(Thread.java:748)
94465
根据上面的测试用例,我们的期望值是100000,但是输出的结果是94465,输出结果小于我们的期望值,并且还抛出了一个ArrayIndexOutOfBoundsException异常(异常不是必现)。

1、为什么输出的值和预期的值不一样?
首先看一下StringBuilder和StringBuffer的两个成员变量,这两个成员变量存在于AbstractStringBuilder类中,因为StringBuilder和StringBuffer都继承了AbstractStringBuilder

//存储字符串的具体内容
char[] value;
//已经使用的字符数组的数量
int count;
在看一下StringBuilder的append方法:

@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
StringBuilder的append()方法调用的父类AbstractStringBuilder的append()方法

public AbstractStringBuilder append(String str) {
if (str == null)
return appendNull();
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
}
count += len不是一个原子操作。假设这个时候count值为10,len值为1,两个线程同时执行到了第七行,拿到的count值都是10,执行完加法运算后将结果赋值给count,所以两个线程执行完后count值为11,而不是12。这就是为什么测试代码输出的值要比10000小的原因。

2、为什么会抛出ArrayIndexOutOfBoundsException异常
我们看回AbstractStringBuilder的append()方法源码,ensureCapacityInternal()方法是检查StringBuilder对象的原char数组的容量能不能盛下新的字符串,如果盛不下就调用expandCapacity()方法对char数组进行扩容。

private void ensureCapacityInternal(int minimumCapacity) {
// overflow-conscious code
if (minimumCapacity - value.length > 0)
expandCapacity(minimumCapacity);
}
扩容的逻辑就是new一个新的char数组,新的char数组的容量是原来char数组的两倍再加2,再通过System.arryCopy()函数将原数组的内容复制到新数组,最后将指针指向新的char数组。

void expandCapacity(int minimumCapacity) {
//计算新的容量
int newCapacity = value.length * 2 + 2;
//中间省略了一些检查逻辑
...
value = Arrays.copyOf(value, newCapacity);
}
Arrys.copyOf()方法

public static char[] copyOf(char[] original, int newLength) {
char[] copy = new char[newLength];
//拷贝数组
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
AbstractStringBuilder的append()方法源码的第六行,是将String对象里面char数组里面的内容拷贝到StringBuilder对象的char数组里面,代码如下:

str.getChars(0, len, value, count);
getChars()方法

public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
//中间省略了一些检查
...
System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}
拷贝流程见下图

假设现在有两个线程同时执行了StringBuilder的append()方法,两个线程都执行完了第五行的ensureCapacityInternal()方法,此刻count=5。

这个时候线程1的cpu时间片用完了,线程2继续执行。线程2执行完整个append()方法后count变成6了

线程1继续执行第六行的str.getChars()方法的时候拿到的count值就是6了,执行char数组拷贝的时候就会抛出ArrayIndexOutOfBoundsException异常。

至此,StringBuilder为什么不安全已经分析完了。如果我们将测试代码的StringBuilder对象换成StringBuffer对象会输出什么呢?

100000
当然是输出10000啦!

那么StringBuffer用什么手段保证线程安全的?
@Override
public synchronized StringBuffer append(String str) {
toStringCache = null;
super.append(str);
return this;
}

原文地址:https://www.cnblogs.com/try-chi/p/12566369.html