Java – imagine a real concurrency scenario where StringBuffer should be used instead of StringBuilder?

I know the difference between StringBuffer and StringBuilder read here!

Usually, as Javadoc says,

However, the Javadoc of StringBuilder also says:

So, I want to know, does the StringBuffer preference really exist? Since variable strings are mainly used for a single thread, anyone can give me a concurrent real-world scenario. Do you prefer StringBuffer?

Solution

The reason why StringBuffer is thread safe is that on the day of designing the first version of the Java API, people approached concurrency in a different way from today The popular view is that objects should be thread safe - because Java supports threads, people may use any JDK class in multiple threads Later, when Java began to optimize execution time, the cost of unnecessary synchronization blocks began to become a problem, so the new API was designed to be asynchronous After a long time, the JVM began to optimize locking so that undisputed locking was basically free, which made the whole decision meaningless

StringBuffer is still thread safe because old code may rely on it to be thread safe This is far from atypical use, but it is conceivable

For example, suppose you are writing a log file adder that forwards log entries to a central server Since we do not want to block the caller while waiting for network I / O, we perform this operation in a dedicated thread Other threads accumulate their log entries in StringBuffer:

class RemoteLogger implements Runnable,Appender {
    final StringBuffer buffer = new StringBuffer();

    void append(String s) {
        buffer.append(s);
    }

    public void run() {
        for (;;) {
            Thread.sleep(100);

            String message = buffer.toString();
            sendToServer(message);
            buffer.delete(0,message.length());
        }
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>