Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imagine a real concurrent scenario where StringBuffer should be used than StringBuilder?

I know the difference between StringBuffer and StringBuilder. read here!

And generally, as the javadoc says,

Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

But, the javadoc of StringBuilder also says:

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that {@link java.lang.StringBuffer} be used

So, I am wondering, is the case that StringBuffer is preferred really existed? And as the mutable string is used mostly in a single thread, can anyone give me an concurrent real-world scenario that StringBuffer is preferred?

like image 916
wxl24life Avatar asked May 20 '13 15:05

wxl24life


People also ask

When should we use StringBuffer instead of StringBuilder and why?

If a string can change and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous, so you have thread-safety. If you don't want thread-safety than you can also go with StringBuilder class as it is not synchronized.

Which is better to use StringBuffer or StringBuilder?

String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.

When should I use string instead of StringBuilder?

If you are using two or three string concatenations, use a string. StringBuilder will improve performance in cases where you make repeated modifications to a string or concatenate many strings together. In short, use StringBuilder only for a large number of concatenations.

Why should you use StringBuffer objects instead of String objects in a program that makes lot of changes to strings?

The StringBuffer class is used to represent characters that can be modified. The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated.


2 Answers

The reason StringBuffer is thread-safe is that back in the day when the first version of the java api was designed, people approached concurrency differently than nowadays. The prevailing opinion was that objects should be thread safe - because Java supports threads, and people might use any JDK class in multiple threads. Later, when Java was starting to be optimized for execution time, the cost of those needless synchronization blocks started to become a problem, so newer APIs were designed to not be synchronized. Still later, the JVM started to optimize locks to the point that uncontested locks became essentially free, making the entire decision a moot point.

StringBuffer is still thread-safe, because old code might rely on it being thread-safe. That is far from typical use, but conceivable.

For instance, suppose you were writing a logfile appender that forwards log entries to a central server. Since we don't want to block the caller while waiting for network I/O we do that in a dedicated thread. The other threads would accumulate their log entries in a 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());
        }
    }
}
like image 136
meriton Avatar answered Sep 17 '22 15:09

meriton


The simple answer is NO. IMHO there is no sane situation where you would use StringBuffer instead of StringBuilder or another class. Making StringBuffer thread safe can make your code less thread safe because people mistakenly assume that if you have used StringBuffer you code is thread safe when this is not the case.

If you have used StringBuffer, at some point you have to use synchronized, although where is not always clear to most developers, and I have seen many bugs where this (even in mature libraries) wasn't done or wasn't done correctly. It is much better you use StringBuilder and do the locking enternally, consistently.

Why a synchronized StringBuffer was never a good idea.

is the case that StringBuffer is preferred really existed

There is one use case; you have a library which only accepts StringBuffer in the API. This is poor design for the reason mentioned above, but not library is perfect. ;)

like image 22
Peter Lawrey Avatar answered Sep 19 '22 15:09

Peter Lawrey