This is the example i was looking at. The docs say that trying to access the bowBack() method is creating the deadlock , but im new to threads , and i really dont understand why this is happening. In need of some guidance here...

Recommended Answers

All 3 Replies

It is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

So the first instance starts its bow method, which calls the other instance's bowBack
Simultaneously, the other instance starts its bow method, which calls the first instance's bowBack.
So one thread is in the first instance's bow, and cannot run it's bowBack becuase they are synchronised.
At the same time, the other thread is in the second instance's bow, and cannot run it's bowBack because they are synchronised.
Neither bow can finish until its call to the other's bowBack has finished, but neither thread can start bowBack until its bow has finished. So nothing can happen. Everything sits in an infinite "stuck" wait. That's a deadlock.

Don't worry if this seems confusing, because it is confusing. In my opinion thread-related problems are the hardest thing to understand in the whole of programming. You just have to keep thinking it through until it clicks in your brain.

, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.

so if an object MyThread has 100 methods with the synchronized keyword, and one thread accesses just one out of the 100 synchronized methods , all the rest of the 99 methods and the current invoked method are blocked to all other threads in the program ?

i thought only the synchronized method being invoked gets locked/blocked and other threadscan access other methods of the object....

and, thanks a lot for the detailed answer , just what i needed :)

http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html

(basically there is a lock object corresponding to the current instance ("this") for synchronised methods, and when one method has the lock the other threads have to wait for it. Because it has the lock that method can call other synchronised methods for the same intsance, but other threads can't)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.