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,
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 StringBuilder
instance at the same time. In such case you should consider using StringBuffer
instead.
For example, here you should consider using a StringBuffer
instead of StringBuilder
:
public class Test implements Runnable
{
public static StringBuilder sb = new StringBuilder();
public void run ()
{
Test.sb.append ("something");
}
public static void main (String[] args)
{
// start two threads
new Thread (new Test()).start();
new Thread (new Test()).start();
}
}
If you have a StringBuilder
instance which is local to some method, there is no risk of another thread accessing it, so you don't need synchronization, and using StringBuilder
would be more efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With