3

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());
}
4
  • 2
    because StringBuffer is intended to be used in multi-threaded environment (most of its methods are synchronized); StringBuilder is meant for single-threaded use, not synchronized Commented Feb 23, 2020 at 15:36
  • 2
    Which version of Java is this? In the most recent version, the constructors have changed. Commented Feb 23, 2020 at 15:44
  • This is explained in the Javadoc of StringBuilder: "This class provides an API compatible with StringBuffer, but with no guarantee of synchronization". This is the whole reason StringBuilder even exists. Commented Feb 23, 2020 at 16:24
  • This one is JDK8, it has changed in high versions. public String(StringBuffer buffer) { this(buffer.toString()); } Commented Feb 27, 2020 at 14:15

2 Answers 2

2

StringBuffer is designed to be thread-safe and used in multithread applications.

But even with that design it still would be possible that between invoking buffer.getValue() and buffer.length() some other thread could attempt to modify buffer. This means that getValue() would reflect state before that modification but length() state after that modification.

Synchronizing both calls on buffer object via synchronized(buffer) inside String constructor prevents other threads from accessing synchronized methods of that buffer. This especially includes methods able to modify buffer, so it would be impossible to do so in the middle of processing it by String constructor.

Sign up to request clarification or add additional context in comments.

Comments

2

Because the difference of StringBuilder versus StringBuffer is that StringBuffer is thread-safe while StringBuilder is not. Note that thread-safety comes with performance penalty, so StringBuffer should only be used in multi thread usage.

From the official documentation:

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.