Lock database: The principle row-level locking, table locks, optimistic locking, pessimistic locking

First, the relative term.

Table-level lock (lock the entire table)
page-level locking (Lock one)
row-level locking (lock line)
shared locks (S locks, MyISAM called a read lock)
exclusive lock (X lock, MyISAM called a write lock)
pessimistic locking (abstract unreal existence of the lock)
optimistic locking (abstract, unreal existence of the lock)

Two, InnoDB and MyISAM

Mysql 5.5 before using the default MyISAM storage engine, then use InnoDB. View the current storage engine:

show variables like '%storage_engine%';

MyISAM tables use operational data is locked, you update a record will lock the entire table, resulting in lower performance, concurrency is not high. Of course, it also does not exist deadlock.

The biggest difference InnoDB and MyISAM are two points: First, the InnoDB supports transactions ; the second is InnoDB uses row-level locking . That is, you need to change what you do, what you do you can only lock.

In Mysql, the row-level locking is not directly record lock, but lock index . Index divided into the main key index and non-primary key index are two, if a sql statement the operation of the primary key index, Mysql will lock this primary key index; if a statement the operation of the non-primary key index, MySQL will first lock the non-primary key index, then locked related to the primary key index.

InnoDB row lock is achieved by giving the index entry lock, and if there is no index, InnoDB will be recorded by a hidden lock for a clustered index. In other words: If you do not retrieve data through index conditions, then the InnoDB table will lock all the data, the actual results with the same table lock . Because there is no index, find one of the logs have a full table scan, to scan the entire table, you have to lock the table.

Third, the share lock and exclusive lock

1. First: CRUD operations on the database default will add exclusive lock, and the query does not add any locks .

Shared locks: shared locks for a resource, the resource itself can be read, others can read the resource (also shared locks can continue that shared locks can coexist more), but can not be modified. To modify it must wait after all shared locks are completely released. The syntax is:
select * from table lock in share mode

Exclusive lock: for a resource plus exclusive lock itself can be CRUD, other people can not do anything. The syntax is:
select * from table for update- additions and deletions to the exclusive automatic lock

2. The following examples cited (recovery from: http://blog.csdn.net/samjustin1/article/details/52210125 ):

T1 represents a database where a request is executed, T2 request on behalf of another, as can also be understood as a thread T1, T2 to another thread.

Example 1:

T1: select * from table lock in share mode
(assuming that the query will take a long time, so the following examples also assume)

T2: update table set column1='hello'

process:

T1运行(并加共享锁)
T2运行
If T1还没执行完
T2等......
else锁被释放
T2执行
endif

T2 reason to wait, because T2 before executing the update, try to add the table to table an exclusive lock, and database requirements can not coexist on the same shared locks and exclusive resource lock. So T2 must wait T1 executed, a shared lock is released, in order to add exclusive lock before starting the update statement.

Example 2:

T1: select * from table lock in share mode

T2: select * from table lock in share mode

Here T2 T1 without waiting for completion of execution, but can be executed immediately.

Analysis:
Tl operation, the table is locked, such as call lockAT2 run, then add a shared lock on the table, such as call lockB two locks can simultaneously exist (such as a table on the same) on the same resources. This is called shared locks and shared locks are compatible. This means that the shared lock does not prevent other people simultaneously reading resources, but prevent others from modifying resources.

Example 3:

T1: select * from table lock in share mode

T2: select * from table lock in share mode

T3: update table set column1='hello'

T2 T1 runs out you can not wait to run, T3 we have to wait T1 and T2 are run to completion in order to run. Since T3 must release all locks can be shared like T1 and T2 plus exclusive lock and then execute the update operation.

Deadlocks :( Example 4)

T1: begin transelect * from table lock in share modeupdate table set column1='hello'

T2: begin transelect * from table lock in share modeupdate table set column1='world'

Suppose T1 and T2 while achieving select, T1 to table shared locks, T2 also table shared locks, when T1 is select executed, ready to perform update, according to the locking mechanism, T1 is shared locks need to upgrade to an exclusive lock to perform the next Update. before upgrade exclusive lock, must and other shared lock (T2) in the table is released, similarly, T2, etc. are shared lock release T1. Then the deadlock.

Example 5:

T1: begin tranupdate table set column1='hello' where id=10

T2: begin tranupdate table set column1='world' where id=20

Although this statement is the most common, a lot of people think it has the opportunity to produce a deadlock, but in fact depends on the circumstances

If the id is the primary key (main key index default), then this record will suddenly T1 (id = 10 record), then the record is added to the exclusive lock, T2 find Similarly, once positioned by an index to the recording, and id = 20 for recording the added exclusive lock, so that T1 and T2 of each of the respective updating, independently of each other. T2 is no need to wait.

If id is a common one, there is no index. Then when T1 to the line id = 10 plus the exclusive lock, T2 in order to find id = 20, requires a full table scan. But because T1 has been added as a record exclusive lock, resulting in a full table scan of T2 not carry on (in fact, because T1 plus exclusive lock, the database default for the table plus intent locks, T2 to scan the entire table, have to wait the intent lock is released, that is, T1 execution is complete), has led to T2 wait.

Deadlock how to solve it? One way is as follows:

Example 6:

T1: begin transelect * from table for updateupdate table set column1='hello'

T2: begin transelect * from table for updateupdate table set column1='world'

Thus, when the select T1 executed directly on the table plus the exclusive lock, T2 in the implementation of select, T1 and other things need to complete to perform fully implemented. Excluding the deadlock. But when over a third user want to execute a query, but also because of the presence of his row lock had to wait, fourth, fifth user will therefore wait. In large concurrent case, let us wait for the performance to seem too friendly.

So, here we introduce some database update lock (such as the Mssql, attention: Mysql update lock does not exist).

Example 7:

T1: begin transelect * from table (加更新锁)update table set column1='hello'

T2: begin transelect * from table (加更新锁)update table set column1='world'

In fact, the update lock can be seen as a variation of his row lock, but it also allows others to read (and also allows shared locks). But no other operations, unless I release the update lock. T1 to select, plus update lock. T2 running, ready to add update locks, but has found an update lock in there, had to wait. Later, when the user3, user4 ... need to query the data table of the table, and not because of select T1 was blocked in the implementation, can still query, compared to Example 6, which improves efficiency.

And there are plans and intentions lock locks: Intent locks that is: when a row changes, coupled with the exclusive lock automatically, and it will default to the table plus intent lock indicates there are records being locked, this time, others You can not lock the table plus table. If there is no intention to lock the similar indicator of the presence of something, other people have to scan the entire table before adding the lock table to see if there are records being locked and inefficient. The lock these plans, and the programmer has little, did not go to understand.

Fourth, the optimistic and pessimistic locking lock

Case:

An item, the user should purchase inventory -1 and a two or more users at the same time later, at this time three procedures were performed simultaneously read stock is n, then perform some operations, and finally were performed update table setinventory = n-1, then it is clear that this is wrong.

solve:

1. Use the pessimistic locking (that is, in fact, that white exclusive lock)

A program to use when you query inventory exclusive lock ( select * from table where id=10 for update)

Then subsequent operations, including updating inventory, and finally commit the transaction.

B program when querying inventory number, if A has not yet released an exclusive lock, it waits.

Program C with B ......

2. Use optimistic locking (by table design and code to implement)

Is generally added in the product table version version field or timestamp timestamp field

After the program A query to perform the update becomes:
update table set num=num-1 where id=10 and version=23

Thus, to ensure that the data is modified it and check out the data are consistent, and other executive programs have not been modified. Of course, if the update fails, indicating before the update operation, other implementation of the program has been updated inventory number, then you can attempt to retry the update to ensure success. In order to avoid possible update fails, it is reasonable to adjust the number of retries (Ali Baba Development Handbook and no less than three times the number of retries).

Summary: For the above difference, you can see the optimistic and pessimistic locking.

1. Pessimistic locking uses exclusive lock, exclusive lock when the program, other programs are not allowed even queries, resulting in lower throughput. If in the case of more query, use optimistic locking.

2. Optimistic locking updating may fail, and even update failed several times, this is risky. So if you write more frequently, for less demanding throughput, use pessimistic locking.

That is one sentence: read with optimistic locking, pessimistic locking written.



Guess you like

Origin www.cnblogs.com/windpoplar/p/11938432.html