-3

Why StringBuffer is thread safe and why StringBuilder is not. Why the StringBuffer is working best in multi-threading and StringBuilder is in single-threading.

I saw there are methods which are common for both StringBuilder and StringBuffer, then why they are varied in their functions.

ben75
  • 29,217
  • 10
  • 88
  • 134
Dhivakar
  • 2,081
  • 5
  • 15
  • 18

1 Answers1

0

As stated in their javadoc (http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html and http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html), StringBuffer and StringBuilder provider the same set of operations. The only difference between them is that operations in StringBuffer are synchronized, whereas operations in StringBuilder are not.

Because operations in StringBuffer are synchronized, StringBuffer are thread safe, which means that multiple threads can safely operate on the same StringBuffer. In contrast, operations in StringBuilder are not synchronized. If multiple threads need to operate on the same StringBuffer, you need to synchronize these threads manually (or, use StringBuffer).

Synchronization requires the threads to acquire locks. Because synchronized methods perform this extra operation, it is slower than non-synchronized methods.

In summary, if you just want to construct a String, and it does not involve multiple threads, then it is better to use StringBuilder than StringBuffer.

fajarkoe
  • 1,543
  • 10
  • 12
  • Something is wrong in your comment: "operations in StringBuffer are synchronized" ... "In contrast, operations in StringBuffer are not synchronized.". You need to change some StringBuffer to StringBuilder – DavidPostill Jun 28 '14 at 07:17