I don't understand why is this program completing. According to me it should result in a deadlock.
According to me when meth1() method is invoked then it obtains a lock and when meth1() method calls anothermeth() method the lock is still with meth1() method so how come the anothermeth() method is being invoked.
Hi Alton There is the main thread or is it that because the lock is obtained by the thread so the thread can execute any syncronized code on it. Is that what you meant Alton. [ June 16, 2003: Message edited by: Anupam Sinha ]
Locks are owned *per thread*, so invoking a synchronized method from within another method synchronized on the same object will proceed without blocking, releasing the lock only when the outermost synchronized method returns. This per-thread behavior prevents a thread from blocking on a lock it already has, and permits recursive method invocation and invocations of inherited methods, which themselves may be synchronized. (This answer was brought to you by the authors of The Java Progamming Language 10.3.1) [ June 16, 2003: Message edited by: Marlene Miller ]
I think, if a synchronized code has a lock on an object, no other thread can get the lock on that object and therefore can't access the synchronizing code but they have access to the non-synchronizing code. here the meth1() has the lock on the object, and as anothermeth() is also synchronized, they both share the lock on that object. If they share the lock on the object, no harm will be done to the synchronized code because it is guranteed that no other thread can access the synchronized code. Regards, Meghasyam.
Locks operate on a per-thread, not per-invocation basis. A thread hitting synchronized passes if the lock is free or the thread already possesses the lock, and otherwise blocks. (This reentrant or recursive locking differs from the default policy used for example in POSIX threads.) Among other effects, this allows one synchronized method to make a self-call to another synchronized method on the same object without freezing up. That's the way Doug Lea explains it in Concurrent Programming in Java 126.96.36.199. [ June 16, 2003: Message edited by: Marlene Miller ]