0
0
DBMS Theoryknowledge~6 mins

Deadlock handling in databases in DBMS Theory - Full Explanation

Choose your learning style9 modes available
Introduction
Imagine two people trying to pass through a narrow hallway from opposite ends, but each waits for the other to move first. In databases, a similar problem happens when two or more transactions wait forever for resources locked by each other. Deadlock handling solves this problem to keep the database running smoothly.
Explanation
What is a Deadlock
A deadlock occurs when two or more transactions hold locks on resources and each waits for the other to release their lock. This creates a cycle of waiting with no transaction able to proceed. The database must detect and resolve this to avoid freezing.
Deadlock is a cycle of transactions waiting on each other’s locked resources, causing a standstill.
Deadlock Detection
The database regularly checks for cycles in the waiting transactions, often using a wait-for graph. If a cycle is found, it means a deadlock exists. Detection helps the system know when to intervene and break the deadlock.
Deadlock detection finds cycles of waiting transactions to identify deadlocks.
Deadlock Resolution
Once detected, the database chooses one transaction as a victim to roll back or abort. This frees the locked resources and allows other transactions to continue. The choice is usually based on factors like transaction age or cost to roll back.
Deadlock resolution breaks the cycle by aborting one transaction to free resources.
Deadlock Prevention
Some systems prevent deadlocks by ordering resource requests or using timeouts. For example, transactions may request all needed locks at once or wait only a limited time before aborting. Prevention aims to avoid deadlocks before they happen.
Deadlock prevention avoids cycles by controlling how and when locks are requested.
Real World Analogy

Two drivers meet on a narrow bridge from opposite sides. Each waits for the other to back up first, so neither moves. A traffic officer arrives and asks one driver to reverse, letting the other pass and clearing the blockage.

Deadlock → Two drivers stuck waiting for each other on a narrow bridge
Deadlock Detection → Traffic officer noticing the blockage and identifying who is stuck
Deadlock Resolution → Traffic officer asking one driver to reverse to clear the bridge
Deadlock Prevention → Traffic rules that prevent two cars entering the bridge at the same time
Diagram
Diagram
┌───────────────┐       waits for       ┌───────────────┐
│ Transaction A │ ────────────────▶ │ Transaction B │
└───────────────┘                   └───────────────┘
       ▲                                   │
       │                                   ▼
┌───────────────┐       waits for       ┌───────────────┐
│ Transaction C │ ◀─────────────── │ Transaction D │
└───────────────┘                   └───────────────┘

Cycle detected: Transactions waiting in a loop causing deadlock.
This diagram shows transactions waiting on each other in a cycle, illustrating a deadlock situation.
Key Facts
DeadlockA situation where transactions wait indefinitely for resources locked by each other.
Wait-for GraphA graph representing transactions as nodes and waiting relationships as edges.
Deadlock DetectionThe process of finding cycles in the wait-for graph to identify deadlocks.
Deadlock ResolutionBreaking a deadlock by aborting one or more transactions to free resources.
Deadlock PreventionTechniques to avoid deadlocks by controlling lock acquisition order or timing.
Code Example
DBMS Theory
import sqlite3
import threading
import time

conn = sqlite3.connect(':memory:', check_same_thread=False)
cur = conn.cursor()
cur.execute('CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER)')
cur.execute('INSERT INTO accounts VALUES (1, 100)')
cur.execute('INSERT INTO accounts VALUES (2, 100)')
conn.commit()

lock = threading.Lock()

def transfer_a_to_b():
    with lock:
        cur.execute('BEGIN EXCLUSIVE')
        cur.execute('SELECT balance FROM accounts WHERE id=1')
        balance_a = cur.fetchone()[0]
        time.sleep(1)  # Simulate delay
        cur.execute('SELECT balance FROM accounts WHERE id=2')
        balance_b = cur.fetchone()[0]
        if balance_a >= 10:
            cur.execute('UPDATE accounts SET balance = balance - 10 WHERE id=1')
            cur.execute('UPDATE accounts SET balance = balance + 10 WHERE id=2')
        conn.commit()


def transfer_b_to_a():
    with lock:
        cur.execute('BEGIN EXCLUSIVE')
        cur.execute('SELECT balance FROM accounts WHERE id=2')
        balance_b = cur.fetchone()[0]
        time.sleep(1)  # Simulate delay
        cur.execute('SELECT balance FROM accounts WHERE id=1')
        balance_a = cur.fetchone()[0]
        if balance_b >= 10:
            cur.execute('UPDATE accounts SET balance = balance - 10 WHERE id=2')
            cur.execute('UPDATE accounts SET balance = balance + 10 WHERE id=1')
        conn.commit()

thread1 = threading.Thread(target=transfer_a_to_b)
thread2 = threading.Thread(target=transfer_b_to_a)

thread1.start()
thread2.start()

thread1.join()
thread2.join()

cur.execute('SELECT * FROM accounts')
print(cur.fetchall())
OutputSuccess
Common Confusions
Deadlock is the same as a simple lock wait.
Deadlock is the same as a simple lock wait. Deadlock involves a cycle of waiting transactions, while a simple lock wait is just one transaction waiting for a resource.
Deadlock detection always happens instantly.
Deadlock detection always happens instantly. Deadlock detection runs periodically or when certain conditions occur; it is not continuous or instantaneous.
Aborting any transaction will resolve deadlocks equally well.
Aborting any transaction will resolve deadlocks equally well. Databases choose victims carefully based on cost or priority to minimize impact when resolving deadlocks.
Summary
Deadlocks happen when transactions wait forever for each other's locked resources, causing a standstill.
Databases detect deadlocks by finding cycles in waiting transactions and resolve them by aborting one transaction.
Prevention techniques control how locks are requested to avoid deadlocks before they occur.