Sunday 14 May 2017

25. DeadLock

1. What is deadlock
  1. If 2 threads are waiting for each other forever, such type of infinite waiting is called deadlock.
  2. Synchronized keyword is one of the reason for deadlock situation, hence while using synchronized keyword we, we have to take special care.
  3. There is no resolution technique for deadlock, but several prevention techniques.
  4. 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.
  5. If join method calls itself for waiting also comes under deadlock.If t1 thread executes t1.join().
  6. More complicated deadlocks are like.
    1. Thread 1  locks A, waits for B
    2. Thread 2  locks B, waits for C
    3. Thread 3  locks C, waits for D
    4. Thread 4  locks D, waits for A
2. How to prevent  deadlock
  1. In some situations it is possible to prevent deadlocks.
    1. Locks order
    2. Locks timeout
  2. Deadlock occurs when multiple threads need the same locks but obtain them in different order.
  3. If you make sure that all locks are always taken in the same order by any thread, deadlocks cannot occur.
  4. 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

3. Java Program to create Binary Tree