Deadlocks
Deadlocks
Deadlocks
“A deadlock occurs when two or more tasks permanently block each other by each task
having a lock on a resource which the other tasks are trying to lock.”
A deadlock is a special blocking scenario in which two processes get
blocked by each other. Each process, while holding its own resources,
attempts to access a resource that is locked by the other process. This
will lead to a blocking scenario known as a deadly embrace,
In other words, Deadlock is a situation when two or more processes holds a lock on
a different resource try to get a lock on the other process resource which is already
locked. This will eventually create an endless loop. SQL Server knows how to deal
with those kind of situations with the “Deadlock detection” mechanism.
The mechanism continuously (every five seconds) checks the lock monitor thread
and searches for deadlocks.
If a deadlock occurs the mechanism choses a process “victim” and rolls back his
transaction. The victim is the process that its rollback will need the less resources.
Note – If we want we can predefine the process importance level and then the victim
will be chosen by our definition.
Rollback the victim process will enable the other process to finish its transaction and
that will end the loop.
It will be wise to create a “try and catch” mechanism in the processes transactions
that will re-execute the victim process after a few random seconds.
Here is a script as an example of a simple and classical deadlock, which contains
two transactions for each query window.
First Query
-- --Transaction A--
USE AdventureworksCTP3
GO
BEGIN TRANSACTION
--Statement 1--
UPDATE Sales.SalesOrderDetail
SET OrderQty = OrderQty * 2
WHERE SalesOrderID = 43659 and SalesOrderDetailID = 1
--Hold for 10 seconds--
WAITFOR DELAY '00:00:10'
--Statement 2--
SELECT * FROM HumanResources.Department
WHERE DepartmentID = 1
COMMIT
GO
Second Query
USE AdventureworksCTP3
GO
BEGIN TRANSACTION
--Statement 1--
UPDATE HumanResources.Department
SET Name = Name + ' added text'
WHERE DepartmentID = 1
--Hold for 10 seconds--
WAITFOR DELAY '00:00:10'
--Statement 2--
SELECT * FROM Sales.SalesOrderDetail
WHERE SalesOrderID = 43659 and SalesOrderDetailID = 1
COMMIT
GO