Why does class String constructor method with parameter StringBuffer use synchronize block while the constructor with StringBuilder doesn't?
public String(StringBuffer buffer) {
synchronized(buffer) {
this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
}
}
public String(StringBuilder builder) {
this.value = Arrays.copyOf(builder.getValue(), builder.length());
}
StringBufferis intended to be used in multi-threaded environment (most of its methods are synchronized);StringBuilderis meant for single-threaded use, not synchronizedStringBuilder: "This class provides an API compatible with StringBuffer, but with no guarantee of synchronization". This is the whole reasonStringBuildereven exists.