Knowledge of database locks

For different engines to achieve database lock is not the same, and now large-scale projects basically chose InnoDb as the default storage engine, so the film blog articles discuss the contents of the database lock for the InnoDB storage engine.

Because InnoDB database lock and transaction characteristics are closely related, so before we first recall the characteristics of the transaction.

 

ACID properties of a transaction and

  • Atomicity
  • consistency
  • Isolation
  • Endurance

Thanks to the full support transactional characteristics of InnoDB, MySQL we can build on a variety of robust business systems, at the same time, the transaction also increased the cost of treatment, and with the problem of concurrency, the firm brought concurrency problems are mainly the following points:

  • Lost update: two operations in parallel operation, after covering the results of previous operations, it is called lost updates.
  • Dirty read: a transaction before submitting, modified during the transaction data read by other transactions.
  • Non-repeatable read: a thing before submitting, read the previous data in the transaction process, only to find that the data has changed
  • Magic Reading: a thing reread data retrieval seen before in the same conditions, they found other data into the new data

For the above points, there is a general solution idea is: Updates lost through the application completely avoided, while other problems are solved by adjusting the database isolation level, and the means of achieving isolation mechanism of the things is the use of locks

 


 

Exclusive locks and shared locks:

MyIsam achieve a table locks, table locks can be locked against a database table, the lock on the flexibility inferior row locks, table locks are two types of locks: read lock and write lock

InnoDB storage engine to achieve the row locks with table locks (intent locks), line lock can be set to lock the data in units, row locks are also two types of locks: locks are shared and exclusive locks

  • Shared lock: allows a transaction to read a row to prevent other transactions to obtain the same data set exclusive lock, but allows other transactions acquire shared locks.
  • Exclusive locks: Allow him to acquire an exclusive lock transaction update data, preventing other transactions to obtain the same data set exclusive locks and shared locks. But can be a simple query access to exclusive lock acquired data sets

InnoDB addition to other kinds of locks, also has two different ways of locking for update, delete, insert statements, InnoDB will default to involve implicit data sets plus exclusive lock, InnoDB will not be added to the select statement any locks. In addition to implicit locking means other than,

Shared lock can also be obtained by an explicit exclusive lock manner or

  • Shared locks:sql select * from table where ... lock in share mode
  • Exclusive lock:sql select * from table where ... for update

Read the above paragraph. Suppose you are careful enough, you may have been aware of the risks to the deadlock. More than one thread holds a shared lock a data set, and then try to acquire an exclusive lock What happens when?

session 1 -> for age = 26 plus record shared lock

 

CREATE TABLE `test_index_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `birthday` datetime DEFAULT NULL,
  `address` varchar(45) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  `note` varchar(45) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `NAME_ADDRESS` (`name`,`address`) USING BTREE,
  KEY `AGE` (`age`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=283 DEFAULT CHARSET=utf8

 

select * from test_index_table where age = 26 lock in share mode;

 

 

 

 

session 2 -> for recording shared locks age = 26

 

 

 

 

session 1 - Record> age = 26 for acquiring an exclusive lock
because the current data set has been acquired session 2 shared lock, an exclusive lock can no longer acquire, from blocking. (The reason is simple, when the file is read the writing is not allowed)

 

 

 

session 2 - Record> age = 26 for obtaining an exclusive lock
due to the current data set has been acquired shared locks session 1 can no longer acquire an exclusive lock, causing the cycle to wait, database deadlocks operate exit.

 

 

 

Visible, two session acquire a shared lock with a data set, and then were attempting to acquire an exclusive cause circular dependencies that cause database deadlock error, quit operating the lock.

 


 

 

Row lock index

Understand the basic concepts lock light is not enough. In InnoDB row lock is achieved through the lock on the index entry to the index, if there is no index, InnoDB will be recorded by a hidden lock for a clustered index, the other depending on the search conditions for the SQL statements, plus there are three conditions need to lock our grasp

  • Record lock: locking of index entries.
  • Gap lock: lock on the gap between the index entry.
  • Next-key lock: locks noted earlier in the recording gap.

Record lock: locking of index entries. If there is no index entries, use table locks.

InnoDB index for implementation locking means: only retrieve or update data through index conditions, only InnoDB row-level locking, or InnoDB table lock will be used to update the data, greatly reducing the execution performance of concurrent database.

session 1 -> try to search for non-index parts or update acquire an exclusive lock.
NAME_ADDRESS a conventional data table has a composite index of the primary key index. Please note, AGE index I have been deleted.

CREATE TABLE `test_index_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `birthday` datetime DEFAULT NULL,
  `address` varchar(45) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  `note` varchar(45) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `NAME_ADDRESS` (`name`,`address`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=283 DEFAULT CHARSET=utf8

 

 

 Try to Modify statements of non-index entries for this table. Concept before recall: modify statement automatically to the current data set plus an exclusive lock.

update test_schema.test_index_table set name = '王二' where age = 26

 

 session2 -> try to update the record age of 27.
Since the age field is non-indexed field, so session1 use table locks instead of row locks to ensure the consistency of concurrent database access. It caused a session update from blocking 2.

 

session1 -> unlock the tables of session1.

 

 

 

 session2 -> update operation was successful.

 

 

 

Lock for the index, rather than record locking.

InnoDB have already mentioned implementations row lock is based on the index entry. This means that even if you try to acquire an exclusive lock different lines, the use of the same index key, the lock may also cause a conflict.

CREATE TABLE `test_index_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) DEFAULT NULL,
  `birthday` datetime DEFAULT NULL,
  `address` varchar(45) DEFAULT NULL,
  `phone` varchar(45) DEFAULT NULL,
  `note` varchar(45) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `NAME_ADDRESS` (`name`,`address`) USING BTREE,
  KEY `AGE` (`age`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=283 DEFAULT CHARSET=utf8

 

 

 

session1 -> for age = 29 and address = tokyo acquire an exclusive lock.
It is easy to come by observing the table this time we expect to obtain an exclusive lock sets of data should be recorded id = 150.

 

 

 

session1 -> for age = 29 and address = Beijing acquire an exclusive lock.
Id = 149 attempts to update the record of the operation actually blocked.

 

 

 

Update different rows of data sets, it has had an exclusive lock blocking reason is actually very simple. Since the row lock mysql implementation based on the index, so that 149 and 150 corresponding to the index entry is actually the same. So session2 attempting to acquire an exclusive lock when the operation is blocked session1.

 

next-key 锁

When using the range conditions rather than equal conditions to obtain an exclusive lock, innoDB will meet the requirements of all the data lock. For the recording but within the conditions do not exist, called a gap. innoDB this gap will be locked. Further, when using an equal search condition, the search condition if the value of the recording itself does not exist as specified, then the index entry corresponding to this value will be locked.

session 1 -> age> = 25 index entries acquire an exclusive lock

 

 

session 2 - index entry> age = 39 acquires an exclusive lock
due to the operation session1 produces a next-key lock operation is blocked because the

 

 

 

session 1 -> release the lock.

 

 

session 2 -> operation executed successfully. While giving age = 39 index entries increased next-key locks.

 

 session 1 -> age = trying to update a record corresponding to the index entry 39.
Reasons session next-key lock step 2, this operation is blocked.

 

 

 

Seen, those who will cause next-key lock operations need to be carefully considered. Bit, it'll greatly reduce concurrency database performance. You might think to achieve next-key lock is not defective. An important reason, however, mysql innoDB achieve next-key lock is to prevent the transaction phantom reads. When in the presence of next-key, the execution of external affairs no matter how much data is inserted into the insert will not read the new data set before the transaction commits, thus ensuring the consistency of the transaction.

Check InnoDB row lock contention

Row lock on the competition to check InnoDB_row_lock state variable analysis system.

show status like "innodb_row_lock%"

 

If the lock is a serious competition, and innoDB_row_lock_time_avg innoDB_row_lock_waits value is relatively high, the lock to view the situation through information_schema tables in the database.

 

select * from information_schema.innodb_locks

 

 

 

postscript

Database optimization methods section of this article came to an end. Developing web applications no matter what language you use, are inseparable from the support of the database. Bottlenecks large web applications often end up in the IO process, engineers understanding of the database is actually developed than proficient in a language more important.
Unfortunately, many of the company's technical staff, and even the interviewer for database knowledge into the system are still not enough attention, often in the interview for some languages [back to the word in question the wording of several pesters]. In my opinion, a good engineer the most important quality than this: Write maintain strong, easy to read, reliable programs, made neat concise document.

Finally, the knowledge of this series is very important for developers. With this knowledge points to be considered as a basic entry-relational database, called a qualified web back-end engineer, wrote the qualified applications.

 

Reference books
"in layman's language mysql"

Original URL: https://www.jianshu.com/p/69ed3b9d858c

Guess you like

Origin www.cnblogs.com/hetaoyuan/p/11654192.html