Question: In [this](https://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer-in-java) tutorial it is given that StringBuffer is synchronized and StringBuilder is not

1. Can a class be synchonized ?
2. I know that synchronized methods are locked for particular thread and non synchronized are not.But how does a performance of the programe is increased with non-syncronized method?
3. Code from [here](https://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer-in-java)

```
 public class Main {
    public static void main(String[] args) {
        int N = 77777777;
        long t;

    {
        StringBuffer sb = new StringBuffer();
        t = System.currentTimeMillis();
        for (int i = N; i --> 0 ;) {
            sb.append("");
        }
        System.out.println(System.currentTimeMillis() - t);
    }

    {
        StringBuilder sb = new StringBuilder();
        t = System.currentTimeMillis();
        for (int i = N; i --> 0 ;) {
            sb.append("");
        }
        System.out.println(System.currentTimeMillis() - t);
   }
  }
}

```

gives the numbers of `2241 ms` for `StringBuffer` vs `753 ms` for `StringBuilder`.

and accoding to [this](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/StringBuffer.java) the extracode is the synchronised keyword in StringBuffer.Does this synchronised keyword cost the extra 1488ms and if so then should we always prefer StringBuilder instead of StringBuffer?

Thanks in advance.

Answer: 
No, a class cannot be synchronized. It should say that `StringBuffer` is thread-safe instead.

Synchronizing involves extra steps, so there's obviously a tiny performance hit. However, that's not where you want to start optimizing. Also, uncontended synchronizing is supposed to be fast, so using a `StringBuffer` instead of `StringBuilder` in most cases wouldn't make any difference.
1. I'm not sure what you mean by "Can a class be synchronized?" but in general classes can be designed to be thread safe. This usually has some performance penalty involved. Using the synchronized keyword is the most basic way of achieving thread safety.
2. The exact performance penalty will depend on lots of things. One of the answers to the question you linked to gives a benchmark of StringBuffer versus StringBuilder.