True or False? A synchronized method cannot call another synchronized method in its body. The answer given is false! But I don't understand how? Won't it first have to release the lock before calling another synchonized method? Please help, Derek.
Aru Ven
Ranch Hand
Joined: Sep 28, 2000
Posts: 199
posted
0
Derek, I think u r right,,,,, A synchronized method can call another synchronized method.....& the lock will be released when the method is called. Anyone plz correct .... If I am wrong.... Aruna
lakshmi nair
Ranch Hand
Joined: Oct 11, 2000
Posts: 63
posted
0
It is true that you can call another synchronized method within a synchronized method. But I dont think it releases the lock before calling the other method. The lock is on the same object. So,why is it required that we release the lock and acquire it again? Lakshmi
Paul Anilprem
Enthuware Software Support
Ranch Hand
Joined: Sep 23, 2000
Posts: 2912
posted
0
Calling another sync. method of the same class from within the body of a sync. method does not create any problem because Java allows "re-accuring" of locks. As the thread already owns the lock, it allows the thread to execute other sync. method without having the thread to release and then re-accuire the lock. It can execute a sync. method in the same way it would have executed a non-sync. method. HTH, Paul.
Derek, Sorry to mislead u..... I was going through an earlier disscussion of threads & I stumbled upon this. Yes. A thread can obtain the SAME OBJECT LOCK more than once. It can also obtain MORE THAN 1 OBJECT's LOCK at a time. In other words, a thread can have multipile locks in its hand. THese multiple locks may be obtainted by acquiring the same object's lock more than once OR obtaining one lock per object and more than 1 objects at the same time. For example case 1: lock_on_this and lock_onthis and lock_on_this synchronized void m1 () { synchronized(this) { synchronized(this) {} } } case 2 : lock_on_this & lock on objectRef1 and lock_onObjectref2 synchronized void m1 () { synchronized(objectRef1) { synchronized(objectRef2) {} } } HTH, Aruna