Mysql-depth understanding of the lock and transaction isolation level

A lock

1, the lock is defined

    It is a lock that is used to coordinate multiple threads or processes concurrently use the same shared resource mechanism

2, the lock classification

  •  From a performance classification: optimistic and pessimistic locking
  • Classification from the database operation type: read and write locks
  • From the particle size classification operations: Table and row locks

Performance from the 2.1 classification

2.1.1 optimistic locking
    Optimistic locking operation when the name suggests is very optimistic that the operation will not have concurrency problems (no other threads to modify the data), it will not be locked. But when the judge will update the other thread again until it has no data can be modified, usually a version number or CAS mechanism algorithm.
The version number 2.1.1.1 Mechanism
 Method to realize:
  • When removing the recording, obtaining the current version
  • When updating, to bring this version
  • When performing the update, set version = newVersion where version = oldVersion
  • If the version does not, on the update fails
version can customize, you can also use the timestamp as the version number
Example SQL:
update table set name = 'anna',version = version+1 where id = #{id} and version = #{version}
 
 
2.1.1.2 CAS algorithm
    Another technique optimistic locking, when multiple threads attempt to use the CAS simultaneously update the same variable, only one thread can update the value of the variable table, while other threads have failed, failed and will not chant thread hang, and We are being told in this competition fails, and you can try again.
CAS operation includes three operands:
  • You need to read and write memory location V
  • A comparison is expected to original value
  • B intends to write the new value
If the memory location with the expected value of the original value V A match is written to memory location B and V A Alternatively, if A does not match the expected original value no operation. In either case, he will return the value of the position (in some special cases of CAS CAS successful return only if, without extracting the current value) before the CAS instruction. This fact, and optimistic locking conflicts when checking + principle of consistent data updates.
2.1.2 pessimistic locking
    Always assume the worst case, each taking data would think that other thread changes, so will be locked. Once locked, execution of different threads simultaneously, only one thread of execution, other threads in the entrance waiting to know the lock is released.
Pessimistic locks are widely used in JAVA and Mysql
  •     MYSQL read lock, write lock, line lock, etc. 
  •     Java's synchronized keyword

Recommendations:
    Read much conflict probability is small, use optimistic locking
    Write locks, big chance of conflict, use pessimistic locking

2.2 Classification operation type from the database

2.2.1 read lock
    Read lock allows other transactions in the locking query operation, but not modify, operate, namely shared lock.
2.2.2 Write Lock
    Write lock when the lock is not allowed to conduct any operations other things, that an exclusive lock.

From the particle size classification operations 2.3

2.3.1 table lock
    As the name implies, it will lock the entire table, locking in this way a large particle size, block lock, overhead is small, no deadlock. However, the implementation of concurrent low efficiency, prone to locking conflicts.
2.3.2 row lock
    Rows row lock will be operated lock, locked in this way small size, locking slow, big spending, may produce a deadlock. But the concurrent implementation of high efficiency, not prone to locking conflicts.
    For index for record locking instead of row locks innodb. If the index fails, it will upgrade from row locks to a table lock.

Mysql in the MyISAM engine only supports table locks, each time a query will be on the table plus the lock and modify the operation of the write-lock. MyISAM does not support transactions and row lock, while innodb support row-level locking and transactions, which is the biggest difference between MyISAM and Innodb.

Second, the transaction

1, the definition of a transaction

    A logic processing unit consisting of a set of SQL statements in the transaction.

2, the characteristics of the transaction

    Transaction has four properties: atomicity, consistency, isolation, durability.
  • Atomicity: all the operations in the transaction should be atomic, i.e. either perform or not perform
  • Consistency: refers to the data provided before and after the operation performed consistency. This means that all the relevant rules must be applied to the modified data transactions to ensure data integrity. At the end of the transaction, all data structures must also be correct.
  • Isolation: each transaction has its own independent intermediate state of the environment, the transaction is not visible to the outside world and vice versa.
  • Persistence: When the transaction commits, its changes to the database data persistent, even after the database down to restart the data status of the database should still be the result after the transaction commits.

3, deal with problems caused by concurrent transactions

  • Lost updates: When two or more transactions select the same row, and then selected based on the initial value to update the row, because each transaction not know the existence of other matters, lost updates problem occurs - last updated coverage there are other firms to do the update.
  • Dirty read: read transaction to modify the value of the other matters but not submitted, and after that transaction has been rolled back, then the data read by the current transaction is dirty, do not meet the transactional consistency.
  • Non-repeatable read: at the beginning of the current transaction reads a row of data, and after that transaction commits an update to the line in the other, then when the transaction data again to read the same line, and read the result the first difference, or is this a record has been deleted, this phenomenon is called non-repeatable read.
    That transaction reads data to other transactions submitted does not comply with isolation.
  • Magic Reading: A reading transaction data to the new transaction B has been submitted does not comply with isolation

4, the transaction isolation level

    In order to solve the problems caused by concurrent transactions, mysql provides four transaction isolation level in order for us to choose.
  • Uncommitted Read (read uncommit): to modify the transaction can read uncommitted
  • Read Committed (read commit): can be read to modify the committed transactions
  • Repeatable read (repeatable read): Transaction in progress will not be read to modify other committed transactions will only use the snapshot when the first query results obtained. Used here to MVCC (multi-version concurrency control) mechanism to achieve this effect.
  • Serialize (Serializable): the transaction into a serial form to perform at this level will be locked tables, so the situation does not appear phantom read concurrency sectors such isolation is very low, less likely to develop species used.
    The more strict transaction isolation level of the database, then the concurrent side effects caused by the smaller, but the efficiency is also lower concurrently executing, because the transaction isolation level is to a certain extent, the transaction "serialized" in, which is obviously "concurrency" in contradiction.
    So it should be reasonable to choose the transaction isolation level to select the sensitivity of the data according to business scenarios.
 
Gap locks: locks can be avoided using the phantom read gap at the isolation level repeatable read, using the following SQL statement
update account set name = 'tufeu' where id>=5  and id < 7;
在事务开头执行这一语句,可以使得其他事务无法在当前事务未提交前在id为5到7之间插入数据,这就是间隙锁
当然如果你不想真的修改数据的话,请保证间隙锁范围内没有数据。
 
 
In seesion_1 kinds gap lock
In session_2 insertion of new data types because it is a new id id is incremented 6, in the lock range of the gap, resulting in time-out is blocked, the insert fails.
不过由于大部分场景下不需要处理幻读的情况,所以平时要尽量避免间隙读,因为这样的确会降低并发效率
MVCC机制:
    mvcc机制底层由undo log实现,这里以一种较为简单的方式说明机制
首先要明确每个事务都有一个自己的id,事务的id只有在事务执行第一条sql语句时才会分配,mysql的事务id分配严格按照事务的创建顺序来进行。
我们可以看作每一条数据都有两个隐藏的字段创建事务id和删除事务id(可为空)
当我们修改一条数据的时候,不会直接修改,而是新增一条修改过后的数据id和原数据一致(这里是假设不是真实实现,不考虑id重复这个问题)
当我们删除的时候,会将当前做删除操作的事务id记录再”删除事务id“列上
当我们查询一条记录是,会创建一个查询快照,记录此刻的最大已提交事务id。
当我们再次查询的时候会在mysql底层带上过滤条件,创建事务id<=max(当前事务id,快照点已提交最大事务id) and 删除事务id>max(当前事务id,快照点已提交最大事务id)
查询结果不一定唯一,以创建事务id最大的那个为准。
id name balacne create_id del_id
1  a	100	11
2  b	200	12    12
3  c 	300	12
1  a	120	14
 
比如上面这几行数据,假如我们事务id为11 和 12 新增前三条数据,然后新开一个事务id为13的事务,进行查询操作select * form account,的到一个快照,并获得当前的最大已提交事务id为12,不去提交13,新创建一个事务id14,修改id为1的语句,这个时候,mysql会新增一条数据为修改过后的样子,有其事务创建id为14,这个时候我们用事务13去查询,查询语句回事 select * from account where 创建事务id<=max(当前事务id(13),快照点最大提交id(12)) and 删除事务id>max(当前事务id(13),快照点最大提交id(12)),如果没有删除事务id则忽略这个条件,这个时候应该可以看出我们查询出来的数据只会是第一条,因为第四条的创建事务id为14。
我们再看id为2的数据,根据上面的sql查询语句,我们可以看出他的删除事务id为12小于max(当前事务id,快照点最大提交id)所以无法查询到该数据。
 
优化建议:
  • 尽可能的让数据检索通过索引完成,避免无索引行锁升级为表锁
  • 合理设计索引,尽量缩小锁的范围
  • 极可能减少检索条件范围,避免间隙锁
  • 尽量控制事务大小,减少锁定资源量和时间长度,设计事务加锁的sql尽量放在事务最后执行
  • 尽可能使用低级别的事务隔离以提升并发效率
 
 
 
 

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">





Guess you like

Origin www.cnblogs.com/qishanmozi/p/e972c92103cf3735872d88657a013df9.html