I am not clear the concept of
Java Thread acquires an object level lock when it enters into an instance synchronized java method and acquires a class level lock when it enters into static synchronized java method.
What does it mean When it says object level lock and class level lock ?
For example:
public class Counter{
private static int count = 0;
private int count2 = 0;
public static synchronized int getCount(){
return count;
}
public synchronized setCount(int count2){
this.count2 = count2;
}
}
getCount() here will lock Counter.class object while setCount() will lock on current object(this). What does that this refer to ? Does that mean when getCount() get called another thread can’t access setCount() since the whole class is locked ?
When you lock on a
staticmethod you are locking on theClassobject itself and there is one of these perClassLoader. In your example,This is locking on the
Counter.classobject and is the same as:If you are instead locking on a method that is not
staticthen you are locking on the instance of the object that owns that method. In your example:This is the same as locking on the particular
Counterinstance and is equivalent to:So if you have 2
Counterobjects,counter1andcounter2, and 1 thread is callingcounter1.getCount()and the other is callingcounter2.getCount()at the same time, then they will both lock on the sameClassobject and one will block the other.But if the 2 threads are instead calling
counter1.setCount(...)andcounter2.setCount()they will be locking on different objects —counter1andcounter2respectively. They will not block each other.As mentioned, it is very bad form to have asymmetry on your setters and getters and it is unusual to have either be
static.No. If
getCount()is called, theCounter.classis locked and whensetCount(...)is calledcounter1orcounter2is locked. The only time a lock blocks a thread is when the same object has been locked by another thread. Just because there is a lock onCounter.classdoes not mean that there is some sort of uber-class lock. The only time that will block another thread is if it too locks onCounter.class.I’d take a moment to read Sun’s great documentation on how
synchronizedworks.