I am quite confused with the term 'synchronized', I've got following from java documentation.
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.
As I know synchronization relates to threads and the way of their access.
Lets say, I have a web application that is utilizing StringBuilder in one of its methods,
- What does no guarantee of synchronisation mean here?
- Should I be worried about anything? When should I be worried about multiple threads? Any examples?
- When should I care about guaranteed and non-guaranteed synchronisation?
- What is an example of having a web application with multiple threads?
An example would be highly appreciated.
Please note I know multiple thread access require synchronization because they need to have access to the same data! I need to have an example for that.
You should care about synchronization if more than one thread can have access to the same
StringBuilderinstance at the same time. In such case you should consider usingStringBufferinstead.For example, here you should consider using a
StringBufferinstead ofStringBuilder:If you have a
StringBuilderinstance which is local to some method, there is no risk of another thread accessing it, so you don't need synchronization, and usingStringBuilderwould be more efficient.