可变性
String
不可变
在 String
中, byte[] value
由 final
修饰
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence,
Constable, ConstantDesc {
/**
* The value is used for character storage.
*
* @implNote This field is trusted by the VM, and is a subject to
* constant folding if String instance is constant. Overwriting this
* field after construction will cause problems.
*
* Additionally, it is marked with {@link Stable} to trust the contents
* of the array. No other facility in JDK provides this functionality (yet).
* {@link Stable} is safe here, because value is never null.
*/
@Stable
private final byte[] value;
...
}
StringBuffer
和StringBuilder
可变
StringBuffer
和 StringBulder
都继承于 AbstractStringBuilder
抽象类,其中的 byte[] value
没有修饰符
abstract sealed class AbstractStringBuilder implements Appendable, CharSequence
permits StringBuilder, StringBuffer {
/**
* The value is used for character storage.
*/
byte[] value;
...
}
线程安全
String 不可变,因此是线程安全的
StringBuilder 不是线程安全的
以 append()
为例,其方法没有修饰符
public final class StringBuilder
extends AbstractStringBuilder
implements Appendable, java.io.Serializable, Comparable<StringBuilder>, CharSequence
{
...
public StringBuilder append(StringBuffer sb) {
super.append(sb);
return this;
}
...
}
StringBuffer 是线程安全的,内部使用 synchronized 进行同步
以 append()
为例,其方法被 synchronized
修饰
public final class StringBuffer
extends AbstractStringBuilder
implements Appendable, Serializable, Comparable<StringBuffer>, CharSequence
{
...
@Override
synchronized StringBuffer append(AbstractStringBuilder asb) {
toStringCache = null;
super.append(asb);
return this;
}
...
}