"StringBuffer is synchronized (or thread safe), but StringBuilder is not," why does this slow down StringBuffer methods?

After reading this - What does β€œsynchronized” mean? I still could not understand why StringBuffer would be slower than StringBuilder in a thread-safe environment. What extra time-consuming work that StringBuffer needs to do makes it slower?

+3
source share
3 answers

There is some small overhead and the release of even an unprotected lock, and elision lock will not work in StringBuffer, even if most instances are not used. thread because an instance may be.

See http://book.javanb.com/java-threads-3rd/jthreads3-CHP-5-SECT-1.html for a description of what a virtual machine should do when it receives and releases locks.

+7
source

Make sure everything works synchronously. Or, more precisely, due to synchronization. Synchronizing a method call means that two different calls to this method (on this object, if it is not static) must enter the method in turn. Thread B cannot enter the synchMeth method until Thread A ends (already in the method).

, , .

+2

JavaDoc

StringBuilder API StringBuffer, . StringBuffer ( , ). , , , StringBuffer, .

StringBuffer StringBuilder

Starting with the release of JDK 5, this class has been supplemented with an equivalent class designed to be used by a single thread, {StringBuilder}. The StringBuilder class should generally be used in preference to this, since it supports all the same operations but is faster because it does not perform any synchronization.

Additional useful link: Difference between StringBuffer and StringBuilder class.

+2
source

All Articles