Deadlock Handling - CSU357 - Shoolini University

Deadlock Handling

1. Deadlock Handling in DBMS

Deadlock is a situation in DBMS where two or more transactions are unable to proceed because each is waiting for one of the others to release a lock. Effective deadlock handling ensures the smooth operation of the database system.

1.1 Deadlock Prevention

Deadlock prevention aims to ensure that the system never enters a deadlock state. There are several strategies for this:

1.2 Deadlock Avoidance

Deadlock avoidance dynamically examines the resource-allocation state to ensure that there can never be a circular wait. The most common algorithm used is the Banker’s algorithm.

1.2.1 Wait-Die Scheme

In this scheme, if an older transaction requests a resource held by a younger one, it waits. Otherwise, it is rolled back (dies).

1.2.2 Wound-Wait Scheme

If an older transaction requests a resource held by a younger one, the younger one is rolled back (wounded). Otherwise, the older transaction waits.

1.3 Deadlock Detection

In deadlock detection, the system allows transactions to request resources and detects deadlocks when they occur. This involves maintaining a wait-for graph and periodically checking it for cycles.

-- Example of detecting deadlocks in SQL Server
SELECT 
    request_session_id, 
    resource_type, 
    resource_associated_entity_id
FROM 
    sys.dm_tran_locks
WHERE 
    resource_type = 'OBJECT'

1.4 Deadlock Recovery

Once a deadlock is detected, the system must recover from it. This involves aborting one or more transactions to break the deadlock. The aborted transactions are rolled back and restarted.

1.5 Implementation Methods in SQL

SQL-based systems have specific commands and settings to handle deadlocks. Here are a few examples:

1.5.1 Setting Deadlock Priority
-- Set the deadlock priority in SQL Server
SET DEADLOCK_PRIORITY HIGH;
-- Other possible values are LOW and NORMAL
1.5.2 Detecting Deadlocks
-- Enable deadlock graph in SQL Server for analysis
DBCC TRACEON (1222, -1);