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.
**Can a class be synchonized ?**

Yes, you can synchronize on the class Object (Assuming you meant the class Object). When you synchronize on the `static fields or static members` of a class, then the Class Object itself will be synchronized. So, no two threads can access the class level fields / methods at the same time.

**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?**

Synchronization comes at the expense of locking and releasing the Object's monitor, it also prevents code *restructuring* by JVM (done for better performance).