2

I am taking Algorithms implementation class. And my teacher mentioned StringBuffer and StringBuilder, he said StringBuffer is safer than StringBuilder because in terms of threading. Is that true? And if so, what does that mean? I've looked up this question and lots of the answers mentioned synchronizing. Can anyone explain what that means and how does that make StringBuffer safer than StringBuilder?

Jackson Wang
  • 61
  • 1
  • 9
  • See [What is thread safe in Java](http://stackoverflow.com/q/6324085/4125191) – RealSkeptic Sep 16 '15 at 14:18
  • 1
    Also note that this doesn't mean you should prefer using `StringBuffer` to `StringBuilder`. Quite the contrary - whenever you use it locally, in a single thread, always prefer `StringBuilder`. Use `StringBuffer` only where you need to share the string-building object between threads. – RealSkeptic Sep 16 '15 at 14:21
  • 1
    You almost never need the "extra safety" of `StringBuffer`, and it just incurs extra performance cost with no benefit. – Louis Wasserman Sep 16 '15 at 14:36

2 Answers2

5

StringBuffer has all methods synchronized.

From java doc:

A thread-safe, mutable sequence of characters

Synchronization is a system to synchronize thread access to portion of code so that at most one thread can execute a synchronized block.

If your code is not multithreading or simply if the StringBuffer you are using is not shared between threads use StringBuilder. It is faster.

From javadoc of StringBuilder:

A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

Since all of its methods are synchronized, it means that even if you have 100 threads (or more) using and modifying it at the same time, it will perform each operation fully before handling other requests. With a StringBuilder you have no such guarantees.

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80