面试官Q1:请问StringBuffer和StringBuilder有什么区别?
这是一个老生常谈的话题,笔者前几年每次面试都会被问到,作为基础面试题,被问到的概率百分之八九十。下面我们从面试需要答到的几个知识点来总结一下两者的区别有哪些?
继承关系?
如何实现的扩容?
线程安全性?
继承关系
从源码上看看类StringBuffer和StringBuilder的继承结构从结构图上可以直到,StringBuffer和StringBuiler都继承自AbstractStringBuilder类
如何实现扩容
StringBuffer和StringBuiler的扩容的机制在抽象类AbstractStringBuilder中实现,当发现长度不够的时候(默认长度是16),会自动进行扩容工作,扩展为原数组长度的2倍加2,创建一个新的数组,并将数组的数据复制到新数组。 1public void ensureCapacity(int minimumCapacity) {
2 if (minimumCapacity > 0)
3 ensureCapacityInternal(minimumCapacity);
4}
5
6/**
7* 确保value字符数组不会越界.重新new一个数组,引用指向value
8*/
9private void ensureCapacityInternal(int minimumCapacity) {
10 // overflow-conscious code
11 if (minimumCapacity - value.length > 0) {
12 value = Arrays.copyOf(value,
13 newCapacity(minimumCapacity));
14 }
15}
16
17/**
18* 扩容:将长度扩展到之前大小的2倍+2
19*/
20private int newCapacity(int minCapacity) {
21 // overflow-conscious code 扩大2倍+2
22 //这里可能会溢出,溢出后是负数哈,注意
23 int newCapacity = (value.length << 1) + 2;
24 if (newCapacity - minCapacity < 0) {
25 newCapacity = minCapacity;
26 }
27 //MAX_ARRAY_SIZE的值是Integer.MAX_VALUE - 8,先判断一下预期容量(newCapacity)是否在0<x<MAX_ARRAY_SIZE之间,在这区间内就直接将数值返回,不在这区间就去判断一下是否溢出
28 return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
29 ? hugeCapacity(minCapacity)
30 : newCapacity;
31}
32
33/**
34* 判断大小,是否溢出
35*/
36private int hugeCapacity(int minCapacity) {
37 if (Integer.MAX_VALUE - minCapacity < 0) { // overflow
38 throw new OutOfMemoryError();
39 }
40 return (minCapacity > MAX_ARRAY_SIZE)
41 ? minCapacity : MAX_ARRAY_SIZE;
42}
线程安全性
我们先来看看StringBuffer的相关方法:
1@Override
2public synchronized StringBuffer append(long lng) {
3 toStringCache = null;
4 super.append(lng);
5 return this;
6}
7
8/**
9 * @throws StringIndexOutOfBoundsException {@inheritDoc}
10 * @since 1.2
11 */
12@Override
13public synchronized StringBuffer replace(int start, int end, String str) {
14 toStringCache = null;
15 super.replace(start, end, str);
16 return this;
17}
18
19/**
20 * @throws StringIndexOutOfBoundsException {@inheritDoc}
21 * @since 1.2
22 */
23@Override
24public synchronized String substring(int start) {
25 return substring(start, count);
26}
27
28@Override
29public synchronized String toString() {
30 if (toStringCache == null) {
31 toStringCache = Arrays.copyOfRange(value, 0, count);
32 }
33 return new String(toStringCache, true);
34}
从上面的源码中我们看到几乎都是所有方法都加了synchronized,几乎都是调用的父类的方法.,用synchronized关键字修饰意味着什么?加锁,资源同步串行化处理,所以是线程安全的。
我们再来看看StringBuilder的相关源码:
1@Override
2public StringBuilder append(double d) {
3 super.append(d);
4 return this;
5}
6
7/**
8 * @since 1.5
9 */
10@Override
11public StringBuilder appendCodePoint(int codePoint) {
12 super.appendCodePoint(codePoint);
13 return this;
14}
15
16/**
17 * @throws StringIndexOutOfBoundsException {@inheritDoc}
18 */
19@Override
20public StringBuilder delete(int start, int end) {
21 super.delete(start, end);
22 return this;
23}
StringBuilder的源码里面,基本上所有方法都没有用synchronized关键字修饰,当多线程访问时,就会出现线程安全性问题。
为了证明StringBuffer线程安全,StringBuilder线程不安全,我们通过一段代码进行验证:
测试思想
分别用1000个线程写StringBuffer和StringBuilder,
使用CountDownLatch保证在各自1000个线程执行完之后才打印StringBuffer和StringBuilder长度,
观察结果。
测试代码
1import java.util.concurrent.CountDownLatch;
2
3public class TestStringBuilderAndStringBuffer {
4 public static void main(String[] args) {
5 //证明StringBuffer线程安全,StringBuilder线程不安全
6 StringBuffer stringBuffer = new StringBuffer();
7 StringBuilder stringBuilder = new StringBuilder();
8 CountDownLatch latch1 = new CountDownLatch(1000);
9 CountDownLatch latch2 = new CountDownLatch(1000);
10 for (int i = 0; i < 1000; i++) {
11 new Thread(new Runnable() {
12 @Override
13 public void run() {
14 try {
15 stringBuilder.append(1);
16 } catch (Exception e) {
17 e.printStackTrace();
18 } finally {
19 latch1.countDown();
20 }
21 }
22 }).start();
23 }
24 for (int i = 0; i < 1000; i++) {
25 new Thread(new Runnable() {
26 @Override
27 public void run() {
28 try {
29 stringBuffer.append(1);
30 } catch (Exception e) {
31 e.printStackTrace();
32 } finally {
33 latch2.countDown();
34 }
35
36 }
37 }).start();
38 }
39 try {
40 latch1.await();
41 System.out.println(stringBuilder.length());
42 latch2.await();
43 System.out.println(stringBuffer.length());
44 } catch (InterruptedException e) {
45 e.printStackTrace();
46 }
47 }
48}
测试结果
StringBuffer不论运行多少次都是1000长度。
StringBuilder绝大多数情况长度都会小于1000。
StringBuffer线程安全,StringBuilder线程不安全得到证明。
总结一下
StringBuffer和StringBuilder都继承自抽象类AbstractStringBuilder。
存储数据的字符数组也没有被final修饰,说明值可以改变,且构造出来的字符串还有空余位置拼接字符串,但是拼接下去肯定也有不够用的时候,这时候它们内部都提供了一个自动扩容机制,当发现长度不够的时候(默认长度是16),会自动进行扩容工作,扩展为原数组长度的2倍加2,创建一个新的数组,并将数组的数据复制到新数组,所以对于拼接字符串效率要比String要高。自动扩容机制是在抽象类中实现的。
线程安全性:StringBuffer效率低,线程安全,因为StringBuffer中很多方法都被 synchronized 修饰了,多线程访问时,线程安全,但是效率低下,因为它有加锁和释放锁的过程。StringBuilder效率高,但是线程是不安全的。
各位老铁如果还有别的答案,可以评论留言哈!
转自:https://mp.weixin.qq.com/s/ZFXCaEp4z_uxLjZkhGlEMQ