Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does synchronization means in terms of StringBuilder and StringBuffer classes?

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.

like image 430
Daniel Newtown Avatar asked Mar 15 '23 15:03

Daniel Newtown


1 Answers

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.

like image 144
Eran Avatar answered Mar 18 '23 11:03

Eran