I am struggling to explain \"deadlock\" in threads in easy words, so please help. What could be the best example of \"deadlock\" (say, in Java), and how it does happen in st
Guffa's description is good.
The best way I've found to avoid deadlocks is to only lock around resources that are private to you, and to release the lock before you call anything that you do not have exclusive control over.
The only problem is that this may require you to shift from using locks for maintaing consistency to using compensating actions, but it's probably less likely to cause problems in the long run, anyway.
This article is good to read about this problem.
Dining philosophers - you have 4 people sitting at a table, and 4 chopsticks. You need 2 chopsticks to eat. Imagine each philosopher tries to eat as follows:
Everyone does step 1. Now step 2 is impossible, since each person waits for the one on his right to drop the left, which they won't do. This is deadlock. If they just took turns then they could all eat, but instead they all starve.
Usually the classes of concurrent programming explains deadlock by examples. I think that the problem of the Dining Philosophers will be a good example to use. You can develop this example in Java and explain the occurrence of deadlock when two philosophers holds a left fork and are waiting for the right fork. (or vice versa).
I learned a lot of concepts from concurrent programming using this examples implemented on Java.
Imagine you and your girlfriend quarrelled over who should open the door in order to leave the house.The person who apologises will open the door. She is waiting for you to apologise, you are waiting for her to apologise which results in the couple never leaving the house as both refuse to apologise.
Deadlock happens when you have 2 different resources that 2 different threads need to lock in order to use them. The threads lock them in the opposite order, so it becomes impossible for execution to continue until 1 of the threads backs down.
Wikipedia has a couple good real-life examples of deadlock.
Sample1:
I promised never do promises
Sample2:
Talking with genie of the lamp: My wish is that you never make wishes comes true
Sample3:
recruiter: I will hire you if you explain deadlock.
candidate: If you hire me I will explain what deadlock is about