The difference between database blocking and deadlock

Source: Internet
Author: User

This article from: http://blog.sina.com.cn/s/blog_6f33ee7901018nsd.html

Database blocking and deadlock often occur in the process of program development, how to avoid it? Below through demo simple simulation, the database is blocked and deadlock phenomenon:
One, database blocking:
Database blocking phenomenon: The first connection occupies a resource that is not released, and the second connection needs to obtain the resource. If the first connection is not committed or rolled back,

The second connection waits until the first connection releases the resource. For blocking, the database cannot be processed, so the database operation should be committed in a timely manner or

The user is rolled back.
Demo:
--Create a table
CREATE TABLE TB (ID int,createtime date);
--Inserting test data
INSERT into TB select 1,sysdate from dual;
INSERT into TB select 2,sysdate from dual;
INSERT into TB select 3,sysdate from dual;
Commit

The first connection, not committing or rolling back:
sql> Update TB set id=2 where id=1;

1 row updated

The second connection, which has been running:
sql> Update TB set id=2 where id=1;

Because the first connection occupies the TB table without releasing the resource, the second connection waits for the first connection to release the resource.

Second, database deadlock:
Database deadlock phenomenon: The first connection occupies a resource that is not released, is ready to get the resource occupied by the second connection, and the second connection occupies a resource that is not released.

Prepare to get the resources that the first connection occupies. This phenomenon of mutual possession of resources required by each other is called a deadlock. For deadlocks, the database processing method: Sacrifice A

Connection to ensure the successful execution of another connection.
Demo:
--Create a test table T1
CREATE TABLE T1 (ID int,createtime date);
INSERT INTO T1 select 1,sysdate from dual;
INSERT INTO T1 select 2,sysdate from dual;
INSERT INTO T1 select 3,sysdate from dual;
Commit

--Create a test table t2
CREATE TABLE t2 (ID int,createtime date);
Insert INTO T2 select 1,sysdate from dual;
Insert INTO T2 select 2,sysdate from dual;
Insert INTO T2 select 3,sysdate from dual;
Commit

First connection, run in command window:
Begin
--Modify T1 first
Update T1 set id=2
where id=1;
--Wait 20s
Dbms_lock.sleep (20);
--Re-modify T2
Update T2 Set id=2
where id=1;
End
/
Operation Result:
ORA-00060: Deadlock detected while waiting for resource
ORA-06512: On line 9

A second connection:

Begin
--Modify T2 first
Update T2 Set id=2
where id=1;
--Wait 20s
Dbms_lock.sleep (20);
--Re-modify T1
Update T1 set id=2
where id=1;
End
/
Operation Result:
PL/SQL procedure successfully completed

Because the first connection occupies the table T1, want to get the resources of the table T2, and the second connection occupies the table T2, want to get the table T1 resources, this mutual possession of each other to obtain the capital

The source, which satisfies the deadlock phenomenon. The last first connection reported an exception and the second connection was executed successfully.

------------------------------------------------------

Resources and detections where deadlocks are located:

In two or more tasks in SQL Server, if a task locks a resource that other tasks are trying to lock. can cause permanent blocking of these tasks, resulting in deadlocks.

For example:

L Transaction T1 obtained a shared lock of row R1.

L Transaction T2 obtained a shared lock of row R2.

L then the transaction T1 the row R2 lock, but the T2 completes and releases its shared lock to the R2 before it is blocked.

L T2 the exclusive lock of the request line R1, but the transaction T1 completes and releases it until it is blocked by the shared lock held by R1.

Now T2 and T1 wait for each other, causing a deadlock. In general, the Monitor automatically detects and resolves this problem.

A resource that can deadlock:

Deadlocks occur not only on lock resources, but also on resources:

L Lock . such as pages, rows, metadata, and locks on the application.

L worker Threads . If a queued-waiting task has a resource that blocks all other worker threads, it can also cause a deadlock.

L Memory . Deadlocks can occur when concurrent requests are waiting for memory to be available and the current free memory does not meet their needs.

L Related resources for parallel query execution . Deadlocks can occur between threads when a statement is used by multiple threads to run.

Deadlock Detection:

The default 5 seconds searches All tasks in SQL Server for deadlock detection. If it does, it will select one as the victim and return a 1205 error. It is generally the least expensive transaction as a victim.

The difference between deadlock and blockage:

Blocking: When a transaction requests a lock on a resource that is locked by another transaction, the transaction that makes the request waits until the lock is released by someone else and can apply to the location.

By default, a transaction waits until Lock_timeout is set.

Deadlock: The mutual wait between two or more processes. However, because SQL Server has a database engine deadlock detection scheme, it will eliminate an existing deadlock for at least 5 seconds. The impact on performance is often not blocked seriously.

Problem Locator:

1, trace flag 1204 and trace flag 1222:

To open a tracked statement:

DBCC TRACEON (1222,-1)

DBCC TRACEON (1204,-1)

For the results explained in 1222:

1, deadlock the process of sacrifice: the first sentence of Deadlockvictim=processxxxx, in the XXXX is the victim of deadlock.

2, deadlock occurred process information: The second part of the Process-list

3. Deadlock resource information: In the resource-list of the result

4. Deadlock Graphics Event:

Obtained from SQL Server Profiler, typically combined with 1222 trace flags and SQL Trace.

First, look for 1222 output from errorlog, and find the corresponding connection in the trace according to the time of the output. Then analyze the reason.

Workaround:

Although deadlocks cannot be completely avoided, chances can be minimized:

L Access Objects in the same order.

L Avoid user interaction in the transaction.

L KEEP the transaction short and in a batch process.

L Use the isolation level of the soles of the feet.

L Adjust the execution plan of the statement to reduce the number of lock requests.

Access objects in the same order:

If all concurrent transactions access the object in the same order, the likelihood of a deadlock is reduced.

To avoid user interaction in a transaction:

Avoid writing transactions that contain user interaction, because batches that do not have user intervention run much faster than queries that must wait for the user to respond.

Keep the transaction short and in a batch:

The longer the run time, the longer the wait time, and the higher the chance of a deadlock.

Use the isolation level of the soles of the feet:

Determines whether a transaction can run at a low isolation level. Use a lower isolation level whenever possible.

Adjust the execution plan of the statement to reduce the number of locks requested:

You can find out which resources are consuming more from the execution plan. At this point the number of locks will also increase correspondingly.

The difference between database blocking and deadlock

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.