Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - synchronizing static methods

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?

like image 349
sotn Avatar asked Mar 11 '13 01:03

sotn


People also ask

Do static methods need to be synchronized?

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.

Can a static method be synchronized yes or no?

A static method cannot be synchronized.

What is the difference between synchronized static method and synchronized non static method?

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.

What is the difference between static synchronized and synchronized methods?

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.


1 Answers

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

like image 180
spiritwalker Avatar answered Oct 18 '22 00:10

spiritwalker