Why is synchronized block better than synchronized method?
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.
The difference is in which lock is being acquired:
synchronized method acquires a lock on the whole object. This means no other thread can use any synchronized method in the whole object while the method is being run by one thread.
synchronized blocks acquires a lock in the object between parentheses after the synchronized keyword. Meaning no other thread can acquire a lock on the locked object until the synchronized block exits.
So if you want to lock the whole object, use a synchronized method. If you want to keep other parts of the object accessible to other threads, use synchronized block.
If you choose the locked object carefully, synchronized blocks will lead to less contention, because the whole object/class is not blocked.
This applies similarly to static methods: a synchronized static method will acquire a lock in the whole class object, while a synchronized block inside a static method will acquire a lock in the object between parentheses.