Deadlock in Databases

What is deadlock?

  • A deadlock is a condition that occurs when two or more different database tasks are waiting for each other and none of the task is willing to give up the resources that other task needs.
  • It is an unwanted situation that may result when two or more transactions are each waiting for locks held by the other to be released.
  • In deadlock situation, no task ever gets finished and is in waiting state forever.
  • Deadlocks are not good for the system.

  • deadlock state

    In the above diagram,
  • Process P1 holds Resource R2 and waits for resource R1, while Process P2 holds resource R1 and waits for Resource R2. So, the above process is in deadlock state.
  • There is the only way to break a deadlock, is to abort one or more transactions. Once, a transaction is aborted and rolled back, all the locks held by that transaction are released and can continue their execution. So, the DBMS should automatically restart the aborted transactions.

Deadlock Conditions

Following are the deadlock conditions,
1. Mutual Exclusion
2. Hold and Wait
3. No Preemption
4. Circular Wait

A deadlock may occur, if all the above conditions hold true.

In Mutual exclusion states that at least one resource cannot be used by more than one process at a time. The resources cannot be shared between processes.

Hold and Wait states that a process is holding a resource, requesting for additional resources which are being held by other processes in the system.

No Preemption states that a resource cannot be forcibly taken from a process. Only a process can release a resource that is being held by it.

Circular Wait states that one process is waiting for a resource which is being held by second process and the second process is waiting for the third process and so on and the last process is waiting for the first process. It makes a circular chain of waiting.

Deadlock Prevention

Deadlock Prevention ensures that the system never enters a deadlock state.

Following are the requirements to free the deadlock:

1. No Mutual Exclusion : No Mutual Exclusion means removing all the resources that are sharable.

2. No Hold and Wait : Removing hold and wait condition can be done if a process acquires all the resources that are needed before starting out.

3. Allow Preemption : Allowing preemption is as good as removing mutual exclusion. The only need is to restore the state of the resource for the preempted process rather than letting it in at the same time as the preemptor.

4. Removing Circular Wait : The circular wait can be removed only if the resources are maintained in a hierarchy and process can hold the resources in increasing the order of precedence.

Deadlock Avoidance

  • Deadlock Avoidance helps in avoiding the rolling back conflicting transactions.
  • It is not good approach to abort a transaction when a deadlock occurs.
  • Rather deadlock avoidance should be used to detect any deadlock situation in advance.