Here is a piece of text I found at this link.
"Avoid lock on static methods
The worst solution is to put the "synchronized" keywords on the static methods, which means it will lock on all instances of this class."
Why would synchronizing a static method lock all instances of the class? Shouldn't it just lock the Class?
Not at all. Mostly, the static methods that I have come across do not modify any static variables and hence they do not require to be synchronized.
A static method cannot be synchronized.
When synchronizing a non static method, the monitor belongs to the instance. When synchronizing on a static method , the monitor belongs to the class. In case of non-static synchronized method memory is allocated multiple time whenever method is calling.
In short if you synchronize on a static method you will synchronize on the class (object) and not on an instance (object). That means while execution of a static method the whole class is blocked. So other static synchronized methods are also blocked.
To understand this, the easiest way is to compare how lock works against instance method and static method. Let's say you have class Test.java, which has two methods as follow.
public class Test{
public synchronized void instanceMethod(){
}
public synchronized static void staticMethod(){
}
}
Meanwhile, there are two instances of class Test, testA and testB. And also there are two thread tA and tB trying to access class Test in parallel.
locking on instanceMethod: When tA gets the lock on instanceMethod of testA, tB cannot access the the same method in testA, however tB is still free to invoke instanceMethod in testB. Because the synchronization against instanceMethod is instance level locking
locking on staticMethod: However, when tA gets the lock on staticMethod, the lock has nothing to do with testA or testB, since synchronization on static method is a class level locking. Which means tB cannot access staticMethod at all until tA release the lock
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With