Shared lock, exclusive lock, update lock

Overview of locks

1. Why introduce locks when

multiple users operate concurrently on the database  at the same time , it will bring the following data inconsistency problems:

Lost update
A, B two users read the same data and modify it, and the modification result of one user is destroyed The result of another modification, such as the

dirty reading of the ticket booking system,
user A modified the data, and then user B read the data, but user A canceled the modification of the data for some reason, and the data returned to the original value, at this time B The obtained data is inconsistent with the data in the database and cannot be read repeatedly. User A reads the data, and then user B reads the data and modifies it. At this time, when user A reads the data again, it is found that the two values ​​before and after are inconsistent . The main method is blockade. Lock is to prohibit users from doing certain operations for a period of time to avoid data inconsistency . There are two classifications of locks: 1. From the perspective of the database system: divided into exclusive locks ( That is, exclusive locks), shared locks, and update locks MS-SQL Server uses the following resource lock modes. Lock Mode Description Shared (S) is used for operations that do not change or update data (read-only operations), such as SELECT statements. Update (U) is used in updatable resources. Prevents the common form of deadlock that occurs when multiple sessions are reading, locking, and possibly subsequent resource updates. Exclusive (X) is used for data modification operations such as INSERT, UPDATE, or DELETE. Make sure you don't have multiple updates to the same resource at the same time. Intent locks are used to establish a hierarchy of locks. The types of intent locks are: Intent Shared (IS), Intent Exclusive (IX), and Intent Exclusive Shared (SIX).



















Schema locks are used when performing operations that depend on the table schema. The types of schema locks are: schema modification (Sch-M) and schema stability (Sch-S).
Bulk Update (BU) is used when bulk copying data to a table and the TABLOCK hint is specified.

Shared Locks
Shared (S) locks allow concurrent transactions to read (SELECT) a resource. No other  transaction can modify the data while a shared (S) lock exists on the resource . Once the data has been read, the shared (S) lock on the resource is released immediately, unless the transaction isolation level is set to repeatable read or higher, or the shared (S) lock is held for the lifetime of the transaction with a lock hint.

Update locks Update
(U) locks prevent the usual form of deadlock. The general update pattern consists of a transaction that reads a record, acquires a shared (S) lock on a resource (page or row), and then modifies the row, which requires the lock to be converted to an exclusive (X) lock. If two transactions acquire a shared mode lock on a resource and then attempt to update data concurrently, one transaction attempts to convert the lock to an exclusive (X) lock. A shared-mode to exclusive lock conversion must wait for a period of time because one transaction's exclusive lock is incompatible with another transaction's shared-mode lock; a lock wait occurs. The second transaction attempted to acquire an exclusive (X) lock for an update. The deadlock occurs because both transactions are converted to exclusive (X) locks, and each transaction waits for the other to release the shared mode lock.

To avoid this potential deadlock problem, use update (U) locks. Only one transaction at a time can acquire an update (U) lock on a resource. Update (U) locks are converted to exclusive (X) locks if a transaction modifies the resource. Otherwise, the lock is converted to a shared lock.

Exclusive locks
Exclusive (X) locks prevent concurrent transactions from accessing resources. Other transactions cannot read or modify data locked by an exclusive (X) lock.

Intentional lock
Intentional lock representation  SQL The server needs to acquire a shared (S) lock or an exclusive (X) lock on some underlying resource in the hierarchy. For example, a shared intent lock placed at the table level indicates that the transaction intends to place a shared (S) lock on a page or row in the table. Setting an intent lock at the table level prevents another transaction from subsequently acquiring an exclusive (X) lock on the table containing that page. Intent locks can improve performance because SQL Server checks intent locks only at the table level to determine whether a transaction can safely acquire a lock on that table. Instead of checking the locks on each row or page in the table to determine whether a transaction can lock the entire table.

Intent locks include Intent Shared (IS), Intent Exclusive (IX), and Intent Exclusive Shared (SIX).

Lock Mode Description
Intent Sharing (IS) By placing S locks on each resource, the transaction's intent is to read some, but not all, of the underlying resources in the hierarchy.
Intent Exclusive (IX) By placing X locks on each resource, the transaction's intent is to modify some, but not all, of the underlying resources in the hierarchy. IX is a superset of IS.
Shared with Intent Exclusive (SIX) By placing IX locks on each resource, the transaction's intent is to read and modify some, but not all, of the underlying resources in the hierarchy. Allow concurrent IS locks on top-level resources. For example, a SIX lock for a table places a SIX lock on the table (allows concurrent IS locks) and an IX lock on the currently modified page (places an X lock on the modified row). Although each resource can only have one SIX lock at a time to prevent other transactions from updating the resource, other transactions can read the underlying resources in the hierarchy by acquiring table-level IS locks.

Exclusive lock: Only the program that performs the locking operation is allowed to use it, and any other  operations on him will not be accepted. SQL Server automatically uses exclusive locks when executing data update commands. When there are other locks on the object, it cannot be exclusively locked.
Shared lock: The resource locked by the shared lock can be read by other users, but other users cannot modify it. When executing Select, SQL Server will add a shared lock to the object.
Update lock: When SQL Server is ready to update data, it first locks the data object with update lock, so that the data cannot be modified, but can be read. When SQL Server determines to update the data, it will automatically change the update lock to an exclusive lock. When there are other locks on the object, the update lock cannot be added to it.

2. From the programmer's point of view: divided into optimistic locks and pessimistic locks. Optimistic locking: The work of
relying entirely on the database to manage locks . Pessimistic Locking: Programmers manage lock handling on data or objects themselves. MS-SQLSERVER uses locks to achieve pessimistic concurrency control among multiple users who perform modifications in the database at the same time. The granularity of the three locks is the size of the blocked target. Low concurrency but low overhead The lock granularity supported by SQL Server can be divided into acquiring locks for rows, pages, keys, key ranges, indexes, tables or databases Resource Description RID Row Identifier. Used to lock a row in a table individually. Row locks in key indexes. Used to protect key ranges in serializable transactions. Pages 8 kilobytes (KB) data or index pages. A group of eight data or index pages that are adjacent to an extent. Table The entire table including all data and indexes. DB database. The length of the four-lock time The lock is held for the length of time required to protect the resource at the requested level. 





















The holding time of shared locks used to protect read operations depends on the transaction isolation level. With the default transaction isolation level of READ COMMITTED, shared locks are controlled only during page reads. In a scan, the lock is not released until the lock is acquired on the next page within the scan. If you specify the HOLDLOCK hint or set the transaction isolation level to REPEATABLE READ or SERIALIZABLE, locks are not released until the end of the transaction.

Depending on the concurrency options set for the cursor, the cursor can acquire a shared-mode scroll lock to protect fetches. When a scroll lock is required, the scroll lock is not released until the next fetch or the cursor is closed, whichever occurs first. However, if HOLDLOCK is specified, the scroll lock is not released until the end of the transaction.

The exclusive lock used to protect the update will not be released until the end of the transaction.
If a connection attempts to acquire a lock that conflicts with a lock controlled by another connection, the connection attempting to acquire the lock will block until

the conflicting lock is released and the connection acquires the requested lock.

The timeout interval for the connection has expired. By default there is no timeout interval, but some applications set the timeout interval to prevent waiting indefinitely for five

customizations of locks in SQL Server

1 Handling deadlocks and setting deadlock priorities

Endless waits caused by both having partial blocking rights and waiting for partial blocking held by other users

can use SET DEADLOCK_PRIORITY to control how the session reacts in the event of a deadlock situation. A deadlock situation occurs if both processes lock data, and each process cannot release its own lock until the other process releases its lock.

2 Handle the timeout and set the lock timeout duration.

@@LOCK_TIMEOUT Returns the current lock timeout setting for the current session in milliseconds

The SET LOCK_TIMEOUT setting allows an application to set the maximum time a statement waits for a blocking resource. When the statement wait time is longer than the LOCK_TIMEOUT setting, the system will automatically cancel the blocked statement and return the error message No. 1222 to the application "The lock request timeout period has been exceeded"

Example
The following example sets the lock timeout period to 1,800 milliseconds.
SET LOCK_TIMEOUT 1800

3) Set the transaction isolation level.

4) Use table-level locking hints for SELECT, INSERT, UPDATE, and DELETE statements.

5) To configure the locking granularity of the index,
you can use the sp_indexoption system stored procedure to set the locking granularity used for the index.

Six view the lock information

1 Execute EXEC SP_LOCK to report information about the lock
2 Press Ctrl+2 in the query analyzer to see the lock information

7. Precautions for use

How to avoid deadlock
1. When using transactions, try to shorten the logical processing process of the transaction, and submit or roll back the transaction as soon as possible;
2. Set the deadlock timeout parameter to a reasonable range, such as: 3 minutes to 10 minutes; Automatically give up this operation to avoid process suspension;
3. Optimize the program, check and avoid deadlock phenomenon; 4. Carefully test
all scripts and SPs before the exact version. 5 All SPs must have error handling (via @error) 6 Generally do not modify the default level of SQL SERVER transactions. It is not recommended to forcibly lock to solve the problem. How to lock the row table database? Eight or several lock-related problems 







1 How to lock a row of a table

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SELECT * FROM table ROWLOCK WHERE id = 1

2 Lock a table in the database

SELECT * FROM table WITH (HOLDLOCK)

lock statement:
sybase:
update table set col1=col1 where 1=0 ;
MSSQL:
select col1 from table (tablockx) where 1=0 ;
Oracle :
LOCK TABLE table IN EXCLUSIVE MODE ;
After locking, other people cannot operate until the locked user is unlocked. Use commit or rollback to unlock


a few examples to help Everyone deepens the impression
. Let table1(A,B,C)
ABC
a1 b1 c1
a2 b2 c2
a3 b3 c3

1) Exclusive lock
Create two new
connections and execute the following statement in the first connection
begin tran
update table1
set A='aa'
where B='b2'
waitfor delay '00:00:30' -- wait for 30 seconds
Commit tran
executes the following statement in the second connection
begin tran
select * from table1
where B='b2'
commit tran

If the above two statements are executed at the same time, the select query must wait for the update to be executed before it can be executed, that is, it will take 30 seconds

2) The shared lock
executes the following statement in the first connection
begin tran
select * from table1 holdlock -holdlock artificially locks
where B='b2'
waitfor delay '00:00:30' -- wait for 30 seconds
commit tran

in the second connection Execute the following statements in
begin tran
select A,C from table1
where B='b2'
update table1
set A='aa'
where B='b2'
commit tran

If the above two statements are executed at the same time, the select in the second connection The query can be executed
and the update must wait for the first transaction to release the shared lock and turn it into an exclusive lock before it can be executed, that is, wait for 30

seconds
.E)
DE
d1 e1
d2 e2
execute the following statement in the first connection
begin tran
update table1
set A='aa'
where B='b2'
waitfor delay '00:00:30'
update table2
set D='d5'
where E='e1'
commit tran

execute the following statement in the second connection
begin tran
update table2
set D='d5'
where E='e1'
waitfor delay '00:00:10'
update table1
set A='aa'
where B='b2'
commit tran

is executed at the same time, the system will detect deadlock , and abort the process

to add:
The table-level locking hint supported by Sql Server2000

HOLDLOCK holds a shared lock until the entire transaction is completed, which should be released immediately when the locked object is not needed, equal to the SERIALIZABLE transaction isolation level

NOLOCK statement execution does not issue a shared lock, allowing dirty reads, equal to READ UNCOMMITTED transaction isolation level

PAGLOCK Use multiple page locks where one table lock is used

READPAST Let sql server skip any locked rows, execute the transaction, apply to READ UNCOMMITTED transaction isolation level only skip RID locks, not pages, regions and table lock



ROWLOCK enforces the

use of a row

lock
Instead of the lock generated by sql server itself,

the two procedures for handling application locks

sp_getapplock lock application resources

sp_releaseapplock unlock application resources

Note: The difference between locking one table of the database

SELECT * FROM table WITH (HOLDLOCK) other transactions can read Table, but cannot update and delete

SELECT * FROM table WITH (TABLOCKX) Other transactions cannot read the table, update and delete

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326596852&siteId=291194637