Database deadlock and solving deadlock problem

 

The so-called deadlock <DeadLock>: refers to a phenomenon in which two or more processes are waiting for each other due to competition for resources during the execution process. If there is no external force, they will not be able to advance. At this time, it is called When the system is in a deadlock state or the system has a deadlock, these processes that are always waiting for each other are called deadlocked processes. Since the resource occupation is mutually exclusive, when a process applies for resources, the relevant processes are left without external assistance. , the necessary resources are never allocated and cannot continue to run, which produces a special phenomenon of deadlock. A situation where two or more threads in an executor are permanently blocked (waiting), each waiting for a resource that is occupied and blocked by other threads. For example, if thread A locks record 1 and waits for record 2, and thread B locks record 2 and waits for record 1, the two threads will deadlock. In a computer system, if the resource allocation strategy of the system is improper, it is more common that the program written by the programmer has errors, etc., which will lead to the phenomenon of deadlock due to improper competition for resources. There are various implementations of locks, such as intent locks, shared-exclusive locks, lock tables, tree protocols, timestamp protocols, and more. There are also various granularities of locks, such as locking on a table, or locking on a record. 
The main reasons for the deadlock are: (1) Because of insufficient system resources. (2) The order in which the processes are running and advancing is not appropriate. (3) Improper allocation of resources, etc.
If the system resources are sufficient and the resource requests of the process can be satisfied, the possibility of deadlock is very low, otherwise it will fall into deadlock due to competition for limited resources. Second, processes run in different order and speed, which may also cause deadlocks. There are four necessary conditions for deadlock: (1) Mutual exclusion condition: a resource can only be used by one process at a time.
(2) Request and hold conditions: When a process is blocked due to requesting resources, it will hold on to the obtained resources.
(3) No deprivation condition: The resources that the process has obtained cannot be forcibly deprived before the end of the use.
(4) Circular waiting condition: A cyclic waiting resource relationship is formed between several processes. These four conditions are necessary conditions for deadlock. As long as a deadlock occurs in the system, these conditions must be established, and as long as one of the above conditions is not satisfied, deadlock will not occur. Deadlock release and prevention: 
By understanding the causes of deadlocks, especially the four necessary conditions for deadlocks, you can avoid, prevent and
remove deadlocks to the greatest extent possible. Therefore, in system design, process scheduling, etc., pay attention to how to prevent these four necessary conditions from being established, and how to determine a reasonable allocation algorithm for resources to prevent processes from permanently occupying system resources. In addition, it is also necessary to prevent the process from occupying resources when it is in a waiting state. During the operation of the system, a dynamic check is performed on each resource application that can be satisfied by the system issued by the process, and whether to allocate resources is determined according to the check results. The system may deadlock, it will not be allocated, otherwise it will be allocated. Therefore, reasonable planning should be given to the allocation of resources.

How to Minimize Deadlocks

 

 

Although deadlocks cannot be completely avoided, the number of deadlocks can be minimized. Minimizing deadlocks increases transaction throughput and reduces system overhead because there are only a few transactions:

◆ Rollback, which cancels all work performed by the transaction.

◆ Resubmit by application due to rollback in deadlock.

The following methods can help minimize deadlocks:

◆Access objects in the same order.

◆ Avoid user interaction in transactions.

◆ keep transactions short and in a batch.

◆ Use a low isolation level.

◆ Use binding connections.

Access objects in the same order

Deadlocks are less likely to occur if all concurrent transactions access objects in the same order. For example, if two concurrent transactions acquire a lock on the Supplier table and then acquire a lock on the Part table, the other transaction is blocked on the Supplier table until one of them completes. After the first transaction commits or rolls back, the second transaction continues. No deadlock occurs. Using stored procedures for all data modifications can standardize the order in which objects are accessed.

 

Avoid user interaction in transactions

Avoid writing transactions that include user interaction, because running batches without user interaction is much faster than a user can manually respond to a query, such as a prompt for replying to application request parameters. For example, if a transaction is waiting for user input, and the user goes to lunch or even goes home for the weekend, the user suspends the transaction so that it cannot be completed. This will reduce the throughput of the system because any locks held by the transaction will only be released when the transaction commits or rolls back. Even if there is no deadlock situation, other transactions accessing the same resource will be blocked waiting for the transaction to complete.

 

Keep transactions short and in one batch

Deadlocks often occur when multiple long-running transactions are executed concurrently in the same database. The longer a transaction runs, the longer it holds an exclusive or update lock, blocking other activities and potentially causing deadlocks.

 

Keeping transactions in a batch minimizes network round-trips for transactions, reduces possible delays in completing transactions, and releases locks.

 

Use a low isolation level

Determines whether a transaction can run at a lower isolation level. Performing a committed read allows a transaction to read data that has been read (unmodified) by another transaction without having to wait for the first transaction to complete. Using a lower isolation level (such as committed read) instead of a higher isolation level (such as serializable read) can reduce the time that shared locks are held, thereby reducing lock contention.

 

use bind connection

Using bonded connections enables two or more connections opened by the same application to cooperate with each other. Any locks acquired by the secondary connection can be held like locks acquired by the primary connection and vice versa, and thus do not block each other.

Find out the deadlock-causing process and SQL statement with stored procedure

 

If a deadlock occurs, how can we detect which SQL statement or stored procedure is the specific deadlock? At this point, we can use the following stored procedures to detect, and we can find out the process and SQL statement that caused the deadlock.

 

use mastergocreate procedure sp_who_lockasbegindeclare @spid int,@bl int,@intTransactionCountOnEntry int,@intRowcount int,@intCountProperties int,@intCounter intcreate table #tmp_lock_who (id int identity(1,1),spid smallint,bl smallint)IF @@ERROR<>0 RETURN @@ERRORinsert into #tmp_lock_who(spid,bl) select. 0 ,blockedfrom (select. * from sysprocesses where blocked>0 ) a where not exists(select. * from (select. * from sysprocesses where blocked>0 ) b where a.blocked=spid)union select. spid,blocked from sysprocesses where blocked>0IF @@ERROR<>0 RETURN @@ERROR -- 找到临时表的记录数select. @intCountProperties = Count(*),@intCounter = 1from #tmp_lock_whoIF @@ERROR<>0 RETURN @@ERROR if @intCountProperties=0select. '现在没有阻塞和死锁信息' as message-- 循环开始while @intCounter <= @intCountPropertiesbegin-- 取第一条记录select. @spid = spid,@bl = blfrom #tmp_lock_who where Id = @intCounter beginif @spid =0 select. 'The database deadlock is caused by: '+ CAST(@bl AS VARCHAR(10)) + 'The process number, the SQL syntax for its execution is as follows' elseselect. 'Process ID SPID: '+ CAST(@spid AS VARCHAR(10))+ ' is blocked by ' + 'Process ID SPID: '+ CAST(@bl AS VARCHAR(10)) +', the current process executes The SQL syntax is as follows 'DBCC INPUTBUFFER

 

Two problems related to locking - deadlock and blocking

 

deadlock

 

Deadlock is a condition that can occur in any multi-user system, not just in relational database management systems (RDBMS). A deadlock occurs when two users (or sessions) have locks on different objects, and each user needs a lock on the other object. Each user waits for the other user to release his lock. Microsoft® SQL Server™ detects when two connections are deadlocked. One of the connections was chosen as the deadlock victim. The transaction for this connection is rolled back, and the application receives an error.

 

 

If the deadlocks become a single common event, and their rollbacks cause excessive performance degradation, then a thorough investigation is required again. Use trace mark 1204. For example, the following command starts SQL Server from a command prompt with trace flag 1204 enabled:

c:\\mssql\\binn\\sqlservr -T1204

 

 

All messages are now displayed on the console screen and in the error log when starting SQL Server.

 

Deadlocks can also occur when using distributed transactions.

 

block

 

Any lock-based concurrent system inevitably has characteristics that may block under certain circumstances. Blocking occurs when one connection controls a lock and another connection requires a conflicting lock type. The result is to force the second connection to wait, or to block on the first connection.

 

In this topic, the term "connection" refers to a single login session to a database. Each connection appears as a system process ID (SPID). Although each SPID is generally not a separate process context, it is often used here to refer to a process. Rather, each SPID consists of server resources and data structures that serve requests from a given client's single connection. A single client application may have one or more connections. As far as SQL Server is concerned, there is no difference between multiple connections from a single client application on a single client and multiple connections from multiple client applications or multiple clients. One connection can block the other, whether from the same application or from separate applications on two different clients.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325294773&siteId=291194637