UnderDog UnderDog - 1 month ago 15
Java Question

Why is Synchronized block better than synchronized method?

I have started learning synchronization in threading.

Synchronized method:

public class Counter{

private static int count = 0;

public static synchronized int getCount(){
return count;
}

public synchoronized setCount(int count){
this.count = count;
}

}


Synchronized block :

public class Singleton{

private static volatile Singleton _instance;

public static Singleton getInstance(){
if(_instance == null){
synchronized(Singleton.class){
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}


When should I use Synchronized method and Synchronized block ?
Why is Synchronized block better than synchronized method ?

Answer

It's not a matter of better, just different.

When you synchronize a method, you are effectively synchronizing to the object itself. In the case of a static method, you're synchronizing to the class of the object. So the following two pieces of code execute the same way:

public synchronized int getCount() {
    // ...
}

This is just like you wrote this.

public int getCount() {
    synchronized (this) {
        // ...
    }
}

If you want to control synchronization to a specific object, or you only want part of a method to be synchronized to the object, then specify a synchronized block. If you use the synchronized keyword on the method declaration, it will synchronize the whole method to the object or class.

Comments