1. What is deadlock
- If 2 threads are waiting for each other forever, such type of infinite waiting is called deadlock.
- Synchronized keyword is one of the reason for deadlock situation, hence while using synchronized keyword we, we have to take special care.
- There is no resolution technique for deadlock, but several prevention techniques.
- Example thread t1 locks obj1, thread t2 locks obj2 , 2 threads entered into their own synchronized areas but after entered, t1 need to call synchronized method of obj2, and t2 need to call synchronized method of obj1, so 1 waits obj2 lock and t2 needs obj1 lock.It is the example of dead lock.
- If join method calls itself for waiting also comes under deadlock.If t1 thread executes t1.join().
- More complicated deadlocks are like.
- Thread 1 locks A, waits for B
- Thread 2 locks B, waits for C
- Thread 3 locks C, waits for D
- Thread 4 locks D, waits for A
2. How to prevent deadlock
- In some situations it is possible to prevent deadlocks.
- Locks order
- Locks timeout
- Deadlock occurs when multiple threads need the same locks but obtain them in different order.
- If you make sure that all locks are always taken in the same order by any thread, deadlocks cannot occur.
- Another deadlock prevention mechanism is to put a timeout on lock attempts meaning a thread trying to obtain a lock will only try for so long before giving up.
No comments:
Post a Comment