Question

Is there a reason to use StringBuffer in a single-threaded applications instead of a StringBuilder? Are there any advantages of StringBuffer if we do not count synchronization in applications using multiple threads?

Was it helpful?

Solution

Only reason I can think of is compatibility with pre-1.5 Java (which might still be in use in some larger companies), and code that is to be shared with other platforms that do not support StringBuilder (ie. CLDC).

OTHER TIPS

No. Even in multithreaded applications you wouldn't necessarily need StringBuffer, unless you're actually handling it from multiple threads. And if you are, there's probably better data structures to use.

Is there a reason to use StringBuffer in a single-threaded applications instead of a StringBuilder?

Answer is : No reason.

There is no reason to go with StringBuffer. Below statement is copied from StringBuffer Doc:

As of release JDK 5, this class has been supplemented with an equivalent class designed for use by a single thread, StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all of the same operations but it is faster, as it performs no synchronization.

StringBuilder has non synchronized methods where as StringBuffer has synchronized methods. Hence For single threaded application use of StringBuilder is adviced.

StringBuffer is used only when when we want to thread safety. It is not a good idea to use StringBuffer class for single threaded applications as it will make the processing slow. So, if you aren’t going to use threading then use the StringBuilder class as it’ll be more efficient than StringBuffer due to the absence of synchronization.

You can use StringBuffer in single-thread application, but there is no reason.

Though, modern JIT-comiler very smart, it can eliminated unecessary synchronization and StringBuffer can turn to the StringBuilder. But this can not occur. =)

In general there is no reason to use a StringBuffer ever!

(Even if you have some ancient applications or libraries, usually only the resulting String is passed along...)

What should be a use case for a String to receive input from multiple threads?

One might think about something like logging but if one would need logging in a multithreaded environment there are a lot of solutions which can be used without having to invent one yourself...

So: NO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top