引言
在文章String、StringBuffer、StringBuilder三兄弟中提到了StringBuilder是线程不安全的,这个结论在我接触Java初期就接触到了,牢记在心却说不出来所以然,所以决定看一看源码,挖一挖原因(一挖一麻袋?)。
分析
查看String源码得知,String字符串是存储在一个不可变的char[]数组中,因为是final类型,初始化后就不可以修改,所以讨论String的安全性是没有什么意义的,它根本不会出现并发的情况:
/** The value is used for character storage. */
private final char value[];
我们再看StringBuilder、StringBuffer的源码,发现它们都继承了 AbstractStringBuilder ,底层都是利用可修改的char数组(JDK 9 以后是 byte数组)。StringBuffer通过synchronized关键字保证了其线程安全性。那StringBuilder在多线程下会发生什么情况呢?我们通过一个实例来看一下:
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 100; i++) {// 根据自己电脑性能调整该值
new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 1000; j++) {
stringBuilder.append('1');
}
}
}).start();
}
new Thread().sleep(1000);
System.out.println("这个stringBuilder的长度是多少呢?");
System.out.println(stringBuilder.length());
我们通过代码创建了100个线程(根据自己电脑性能调整,如果结论等于理论值,可适当调大),每个线程做1000次循环,每次增加一个字符'1',理论stringBuilder的长度为100*1000 = 100000,实际结果(结果不可控,每次执行会有差异的可能性):
这个stringBuilder的长度是多少呢?
96762
将线程增加到1000,循环增加到10000时,发现抛出了异常信息(不是必现,可适当调整线程数和循环数):
Exception in thread "Thread-0" java.lang.ArrayIndexOutOfBoundsException: 4606
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:623)
at java.lang.StringBuilder.append(StringBuilder.java:202)
at Test.MainTest$1.run(MainTest.java:11)
at java.lang.Thread.run(Thread.java:745)
这个stringBuilder的长度是多少呢?
9495864
寻因
通过上面的代码我们发现,StringBuilder在多线程并发时可能发生两种错误:
- StringBuilder在多线程并发时,长度小于理论值
- StringBuilder在多线程并发时,会抛出'java.lang.ArrayIndexOutOfBoundsException'(数组越界)的异常信息
问题1:StringBuilder在多线程并发时,长度小于理论值
通过查看Stringbuilder的源码我们知道下面两个参数:
/**
* The value is used for character storage. 用来存放字符串
*/
char[] value;
/**
* The count is the number of characters used. 用来存放数组长度
*/
int count;
我们上面用到了append(String str)方法:
@Override
public StringBuilder append(String str) {
super.append(str);
return this;
}
重写并调用了父类(AbstractStringBuilder)的方法:
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的计算可能是不准确的。假设线程A读取到count=10,线程B也读取到count=10,len = 1,两个线程同时执行"count += len;",最终count = 11,而不是12。这就导致了问题1的发生。
问题2:StringBuilder在多线程并发时,会抛出'java.lang.ArrayIndexOutOfBoundsException'(数组越界)的异常信息
我们看append(String str) 方法的第五行"ensureCapacityInternal(count + len);",这个方法用来判断数组是否需要扩容,当count + len > 当前数组长度时,进行扩容操作。
/**
* This method has the same contract as ensureCapacity, but is
* never synchronized.
*/
private void ensureCapacityInternal(int minimumCapacity) {
// overflow-conscious code
if (minimumCapacity - value.length > 0)
expandCapacity(minimumCapacity);
}
/**
* This implements the expansion semantics of ensureCapacity with no
* size check or synchronization.
*/
void expandCapacity(int minimumCapacity) {
//新的数组长度为原来的两倍加2
int newCapacity = value.length * 2 + 2;
if (newCapacity - minimumCapacity < 0)
//如果两倍加2仍然小于count + len,则扩容到count + len长度;
newCapacity = minimumCapacity;
//如果新长度<0(int类型超过最大值会为负,测试代码见附录1),则新长度为最大整数2^32 - 1
if (newCapacity < 0) {
//若count+len为负,则证明字符长度超过最大整数,数组没办法再扩容,抛出OutOfMemoryError异常。
if (minimumCapacity < 0) // overflow
throw new OutOfMemoryError();
newCapacity = Integer.MAX_VALUE;
}
value = Arrays.copyOf(value, newCapacity);
}
接下来我们看append(String str) 方法的第六行"str.getChars(0, len, value, count);",该方法用来将str拼接进char[]数组中:
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
// 忽略参数校验代码
System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}
在非并发情况下的拷贝过程:
我们来看一下这个拷贝过程在并发情况下会出现什么问题:count=15,len=1,value.length = 16,线程A、B先后执行到第五行"ensureCapacityInternal(count + len);",线程A通过校验后让出CPU,线程B进行校验,此时count仍为15,B仍可通过扩容校验,继续执行拷贝过程,执行完成后count=16,B让出CPU,线程A继续执行拷贝方法,此时的count已经等于16了,因此会抛出数组越界的异常。
参考文章
参考微信推文:StringBuilder为什么线程不安全?
附录
附录1:int类型超过最大值继续增加变为负值
int a = Integer.MAX_VALUE;
System.out.println(a+2);
结果为:
-2147483647