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?
2 Answers
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.
StringBuffertoStringBuilder. Quite the contrary - whenever you use it locally, in a single thread, always preferStringBuilder. UseStringBufferonly where you need to share the string-building object between threads.StringBuffer, and it just incurs extra performance cost with no benefit.