When I use a synchronized method over an instance method, the monitor is associated with ‘this’. On the other hand, when I have synchronized on my class (static) method, the monitor is associated with the class object. What happens when I have a static variable used in a non-static method? Will that be synchronized?
For example,
public class A{
public static int reg_no = 100;
public synchronized void registration(){
A.reg_no = some operation...
}
}
In the above case, what will happen to the static variable reg_no if two or more threads compete for the method registration()?
When annotating a member function with
synchronized, the method is synchronized on the instance of the object. If you want to synchronize on a static variable, you must manually synchronize on the class object:Note that the above obtains two locks, which can lead to deadlocks if any other code obtains the same two locks in the other order. You may wish to remove
synchronizedfrom the method, leaving onlysynchronized (A.class).