Paul,
I tried to answer. Please read the foll. I also handgrafted an example program (after scratched my head a lot
). Participate in this discussion. I post the concept in this post and the Example program in
the very next post so that it doesn't look too long at first.
regds
maha anna
Obtaining lock on an object
--------------------------- - Each object has an associated lock with it.
- This lock is useful ONLY for executing SYNCHRONIZED INSTANCE METHODS as foll.
class MyClass {
synchronized void instSyncMethod1() {}
synchronized void instSyncMethod2() {}
void ordinaryMethod() {}
}
- Whenever a
thread tries to execute a synchronized block it shd FIRST obtain
this mutually exclusive lock. I am saying MUTUALLY EXCLUSIVE here meaning,
at any point of time ONLY ONE thread can have this lock associated with this
object.
- So assuming, Thread1 obtains the lock for an object (object1) of this "Myclass"
class and starts executing the code inside the instSyncMethod1(). So now the
lock is with Thread1
Scenario - 1
------------- - Assume now a TimeSharing Thread Scheduler, stops this Thread1 and schedules
another Thread2.
- Assume Thread2 uses this SAME object and tries to execute synchronized
instSuncMethod2().
- It WILL fail, because the lock is NOT YET free. It is still with Thread1.
SO Thread2 goes back to waiting for lock pool of this Object.
Scenario - 2 -------------
- Instead of the above case, if Thread2 WOULD HAVE tried to execute the
ordinaryMethod() of the SAME OBJECT whose locks is currently helf by
Thread1.
- It WILL SURELY BE successful. Because in order to execute this
ordinaryMethod() , no lock is necessary.
Scenario - 3
------------- - Instead pf Scenario 2, if Thread2 which WOULD HAVE used ANOTHER OBJECT
OF THE SAME CLASS (object2), can still access ANY OF instSyncMethod1(),
instSyncMethod2(), ordinaryMethod()
- Because this object2 is completely another NEW object and it has its OWN
lock which is used by Thread2
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() {}
}
- This staticSyncMethod1() obtains the lock associated with the Class object
for this Myclass as a whole. It is same as the foll
synchronized (Class.forName("MyClass")) {
}
- Assuming Thread1 calls this staticSyncMethod() on object1, then NO OTHER
THREAD can access ANY METHOD on ANY OTHER OBJECT including the object used
by Thread1, UNTIL this Thread1 releases this Class lock.
- This means NO OTHER Thread can call any of the methods in this object,
or any method on any other NEW objects of this SAME class.
****************************************************************
[This message has been edited by maha anna (edited March 31, 2000).]