Maha,
I referred to your earlier post on this topic. Your explanation is excellent. However your explanation in scenario 4 is incorrect.
Scenario - 4
-------------
- Assuming there is another static synchronized method introduced in the
above class like this
class MyClass {
synchronized void instSyncMethod1() {}
synchronized void instSyncMethod2() {}
void ordinaryMethod() {}
static synchronized void staticSyncMethod1() {}
}
As far as I understand, class locks and object locks are entirely
different entities. Suppose a thread THREAD1 obtains a class lock and is executing a static synchronized method, this does not prevent a thread THREAD2 from obtaining an object lock and executing a non-static synchronized method of the same class.
When you think of it, it does make sense, since you cannot acess instance variables from within a static method hence you cannot corrupt any data.
However the other way around is possible, i.e. you can access static variables from within an instance method. Thus when you access static variables from within a non-static synchronized method,
you should also obtain a class lock to prevent data corruption (a thread can obtain both object lock as well as class lock at the same time).
class MyClass {
static Object staticVariable;
synchronized void instSyncMethod1() //obtain object lock
{
synchronized(staticVariable){ //obtain class lock too
//can access static variables in thread-safe manner now
}
}
}