简体   繁体   中英

Why does class String constructor method with parameter StringBuffer use synchronize block while the constructor with StringBuilder doesn't?

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());
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM