Database lock mechanism and lock mechanism
Basic Principles of locks
To ensure data completion and consistency, the database system uses locks to isolate transactions. The basic theories of locks used by various large databases are consistent, but their implementations vary.
From the perspective of concurrent transaction locks, it can be divided into shared locks and exclusive locks. Different from the locked objects, table locks and row locks are generally divided.
Lock
A shared lock is used to read data. It is exclusive. It allows other transactions to read the locked resources at the same time, but does not allow other transactions to update it.
Exclusive locks are also called exclusive locks. They are suitable for data modification. The resources it locks. Other transactions cannot be read or modified.
When a transaction accesses a certain database resource, if a select statement is executed, a shared lock must be obtained first. If an insert, update, or delete statement is executed, an exclusive lock must be obtained, these locks are used to lock the operated resources.
When the second transaction also needs to access the same resource, If you execute the select statement, you must first obtain the share lock. If you execute the insert, update, or delete statement, you must also obtain the exclusive lock. At this time, depending on the type of lock that has already been rotated on the resource, it is determined that the second transaction should wait for the first transaction to unlock the corresponding resource or immediately obtain the lock.
|
Lock already placed on the Resource |
Read the second transaction |
Update the second transaction |
|
None |
Get share lock now |
Obtain the exclusive lock immediately |
|
Shared lock |
Get share lock now |
Wait for the first transaction to unshare the lock |
|
Exclusive lock |
Wait for the first transaction to unlock the exclusive lock |
Wait for the first transaction to unlock the exclusive lock |
1. Shared lock
1. Locking condition: when a transaction executes a select statement, the database system will assign a shared lock to the transaction to lock the queried data.
2. Unlock condition: by default, the database system immediately removes the shared lock after the data is read. For example, when a transaction executes the SELECT * FROM accounts Statement, the database system first locks the first row, reads the first row, unlocks the first row, and then locks the second row. In this way, during a transaction read operation, other transactions are allowed to simultaneously update unlocked rows in the accounts table.
3. compatibility with other locks: If a shared lock is placed on the data resource, the shared lock and update lock can be placed again.
4. Concurrency performance: Good concurrency performance. when data is placed with a shared lock, you can also place a shared lock or update lock. Therefore, concurrency performance is good.
2 exclusive lock
1. Locking condition: when a transaction executes an insert, update, or delete statement, the database system automatically uses an exclusive lock on the data resources operated by the SQL statement. If another lock (any lock) exists for the data resource, it cannot be placed with an exclusive lock.
2. Unlock condition: the exclusive lock can be unlocked only after the transaction ends.
3. Compatibility: the exclusive lock cannot be compatible with other locks. If an exclusive lock has been applied to data resources, no other locks can be placed. Similarly, if other locks have been placed on the data resource, the exclusive locks cannot be placed.
4. Concurrency performance: Needless to say, the worst. Only one transaction is allowed to access the locked data. If other transactions also need to access the data, they must wait until the previous transaction ends and the exclusive lock is lifted, other transactions have the opportunity to access the data.
3. Update the lock
The update lock is used to lock resources that may be modified in the initialization phase, which can avoid deadlocks caused by the use of shared locks. For example, for the following update statement:
|
UPDATE accounts SET balance = 900 WHERE id = 1 |
The update operation involves two steps:
L read the records whose id is 1 in the accounts table.
L perform the update operation.
If you use a shared lock in the first step and upgrade the lock to an exclusive lock in the second step, a deadlock may occur. For example, if both transactions obtain the shared lock of the same data resource, they must upgrade the lock to an exclusive lock. However, they must wait for the other transaction to release the shared lock before upgrading to an exclusive lock, this causes a deadlock.
Update locks have the following features:
L locking condition: when a transaction executes an update statement, the database system first assigns an update lock to the transaction.
L unlock condition: When the Data Reading is complete and the update operation is performed, the update lock is upgraded to an exclusive lock.
L compatibility with other locks: Update locks are compatible with shared locks. That is to say, an update locks and shared locks can be placed for a single resource, but a maximum of update locks can be placed. In this way, when multiple transactions update the same data, only one transaction can obtain the update lock, and then upgrade the update lock to an exclusive lock. Other transactions must wait until the previous transaction ends, to obtain the update lock, which avoids the deadlock.
L concurrent performance: Allows multiple transactions to read the locked resources at the same time, but does not allow other transactions to modify it.
Introduction to MySQL row-level locks, table-level locks, and page-level locks
Page Level: Engine BDB.
Table-level: Engine MyISAM, which is interpreted as locking the entire table and reading at the same time.
Row-level: Engine INNODB, locking a single row of records
At the table level, the entire table is locked directly. During the lock period, other processes cannot perform write operations on the table. If you are writing a lock, other processes are not allowed to read it.
Row-level, which only locks specified records, so that other processes can still operate on other records in the same table.
Page-level, table-level locks are fast, but there are many conflicts, less row-level conflicts, but the speed is slow. Therefore, the compromised page level is used to lock a group of adjacent records at a time.
MySQL 5.1 supports table-level locking for MyISAM and MEMORY tables, page-level locking for BDB tables, and row-level locking for InnoDB tables.
The table locking method for WRITE and MySQL is as follows:
If there is no lock in the table, put a write lock on it.
Otherwise, put the lock request in the write lock queue.
The locking method for READ and MySQL is as follows:
If there is no write lock on the table, place a read lock on it.
Otherwise, put the lock request in the read lock queue.
InnoDB uses row locking and BDB uses page locking. Both storage engines may have deadlocks. This is because, during SQL statement processing, InnoDB automatically acquires row locks and BDB obtains page locks, rather than at transaction startup.
Advantages of Row-level locking:
· There are only a few lock conflicts when different rows are accessed in many threads.
· Only a small number of changes are allowed during rollback.
· A single row can be locked for a long time.
Disadvantages of Row-level locking:
· More memory is occupied than page-level or table-level locking.
· When used in most tables, it is slower than page-level or table-level locking because you must obtain more locks.
· If you often perform group by operations on most data or scan the entire table frequently, it is much slower than other locks.
· With high-level locking, you can easily adjust applications by supporting different types of locking because the lock cost is lower than Row-level locking.
In the following cases, table locking takes precedence over page-level or row-level locking:
· Most of the table statements are used for reading.
· Read and update strict keywords. You can update or delete a row that can be extracted with a single read Keyword:
· UPDATE tbl_name SET column = value WHERE unique_key_col = key_value;
· Delete from tbl_name WHERE unique_key_col = key_value;
· SELECT combines parallel INSERT statements with few UPDATE or DELETE statements.
· There are many scan or group by operations on the entire table without any write operations.
/* ==================================== Mysql lock table type and unlock statement ======== ================================= */
If you want to perform a large number of INSERT and SELECT operations on a table, but parallel INSERT is not possible, you can INSERT records into the temporary table, then, the data in the temporary table is updated to the actual table on a regular basis. You can use the following command:
Copy the Code as follows:
Mysql> lock tables real_table WRITE, insert_table WRITE;
Mysql> insert into real_table SELECT * FROM insert_table;
Mysql> truncate table insert_table;
Mysql> unlock tables;
Row-level locks have the following advantages:
Reduce the conflict lock when multiple threads request different records.
Reduce data changes during transaction rollback.
It is possible to lock a single row of records for a long time.
Row-level locks have the following Disadvantages:
It consumes more memory than page-level locks and table-level locks.
A lock is a mechanism by a computer to coordinate multiple processes or threads to concurrently access a certain resource. The lock mechanisms of different databases are similar. Because database resources are resources shared by many users, how to ensure consistency and effectiveness of Concurrent Data Access is a problem that all databases must solve, lock conflicts are also an important factor affecting the concurrent database access performance. The unlocking mechanism not only enables us to develop and utilize database resources more effectively, but also enables us to better maintain the database and thus improve the database performance.
The locking mechanism of MySQL is relatively simple. Its most notable feature is that different storage engines support different locking mechanisms.
For example, the MyISAM and MEMORY storage engines use table-level-locking; The BDB storage engine uses page-level-locking ), table-level locks are also supported. the InnoDB Storage engine supports both row-level locks and table-level locks. Row-level locks are used by default.
The features of the above three locks can be roughly summarized as follows:
1) Table-level locks: low overhead and fast locking; no deadlocks; large lock granularity, the highest probability of lock conflicts and the lowest concurrency.
2) Row-level locks: high overhead and slow locking; deadlocks may occur; minimum lock granularity, minimum probability of lock conflicts, and highest concurrency.
3) page lock: the overhead and lock time are between table locks and row locks. Deadlocks may occur. The lock granularity is between table locks and row locks, and the concurrency is average.
Each of the three locks has its own characteristics. From the perspective of the lock, table-level locks are more suitable for queries-oriented applications with only a small amount of data updated based on index conditions, such as WEB applications; row-level locks are more suitable for applications with a large number of concurrent updates of a small amount of different data based on index conditions and concurrent queries, such as some online transaction processing (OLTP) systems.
MySQL Table-level locks can be used in two modes: Table Read Lock and Table Write Lock ). What does this mean? When reading a MyISAM table, it does not block read requests from other users to the same table, but blocks write operations on the same table; write operations on the MyISAM table will block read and write operations on the same table by other users.
The read and write operations of MyISAM tables are sequential, that is, they cannot be performed during read operations, and the opposite is true. However, under certain conditions, MyISAM tables also support concurrent query and insertion operations. The Mechanism is to control a system variable (concurrent_insert, when the value is set to 0, concurrent insertion is not allowed. When the value is set to 1, if the MyISAM table has no holes (that is, the table has no rows deleted ), myISAM allows another process to insert records from the end of the table while reading the table; when the value is set to 2, no matter whether the MyISAM table has holes, records can be inserted concurrently at the end of the table.
How is MyISAM lock scheduling implemented? This is also a key issue. For example, if a process requests the read lock of a MyISAM table and another process also requests the write lock of the same table, what will MySQL process preferentially? Studies show that the write process will first obtain the lock (even if the Read Request first goes to the lock wait Queue ). However, this also causes a major defect, that is, a large number of write operations will make query operations difficult to obtain read locks, which may cause permanent blocking. Fortunately, we can adjust the scheduling behavior of MyISAM through some settings. You can specify the low-priority-updates parameter so that the MyISAM default engine gives the Read Request priority and sets its value to 1 (set low_priority_updates = 1) to lower the priority.
The biggest difference between InnoDB locks and MyISAM locks is that they support transactions and use row-level locks. We know that a transaction is a logical processing unit composed of a group of SQL statements. It has four attributes (ACID attributes:
Atomicity: a transaction is an atomic operation unit. Modifications to the data are either performed in full or not all;
Consistent: data must be Consistent at the beginning and end of the transaction;
Isolation: the database system provides a certain Isolation mechanism to ensure that transactions are executed in an "independent" environment not affected by external concurrent operations;
Durable: after a transaction is completed, it modifies the data permanently, even if a system failure occurs.
InnoDB has two modes of row lock:
1) shared lock: allows a transaction to read a row to prevent other transactions from obtaining exclusive locks for the same dataset.
(Select * from table_name where... lock in share mode)
2) exclusive lock: allow the transaction that obtains the exclusive lock to update data and prevent other transactions from obtaining the shared read lock and exclusive write lock for the same dataset. (Select * from table_name where... for update)
In order to allow row locks and table locks to coexist and implement multi-granularity locks, there are also two types of internal intention locks (both table locks), which are intention shared locks and intention exclusive locks respectively.
InnoDB row locks are implemented by locking the index items. That is, InnoDB uses row-level locks only when data is retrieved through index conditions. Otherwise, table locks are used!
In addition, insert and update several important parameters for performance optimization.
Copy the Code as follows:
Bulk_insert_buffer_size
Batch insert cache size. This parameter is for the MyISAM storage engine. this method improves the efficiency when more than 100-1000 records are inserted at a time. the default value is 8 Mb. double the data size.
Concurrent_insert
Concurrent insert. When the table has no holes (records deleted), other processes can insert the read locks at the end of the table when a process obtains the read locks.
The value can be set to 0 and cannot be inserted concurrently. 1. When the table has no holes, concurrent insertion is performed. 2. Concurrent Insertion is performed regardless of whether there are holes.
The default value is 1. The deletion frequency is set for the table.
Delay_key_write
For the MyISAM storage engine, Index Update is delayed. this means that when the update record is updated, the data is first up to the disk, but the index is not up, and the index is stored in the memory. When the table is closed, the memory index is written to the disk. if the value is 0, it is disabled. If the value is 1, it is enabled. enabled by default.
Delayed_insert_limit, delayed_insert_timeout, delayed_queue_size
Delayed insertion: The data is first handed over to the memory queue and then inserted slowly. however, not all storage engines support these configurations. Currently, common InnoDB does not support these configurations, and MyISAM does. increase the value according to the actual situation. Generally, it is enough by default.
/* ================================ MySQL InnoDB Lock table and lock row ================ ================= */
Because InnoDB defaults to Row-Level Lock, MySQL will only execute Row lock (only Lock the selected data example) If a specified Primary Key is specified explicitly ), otherwise, MySQL will execute Table Lock (Lock the entire data form ).
For example, assume that there is a form products, which contains two columns: id and name. id is the primary key.
Example 1: (specify the primary key and use this document, row lock)
Copy the Code as follows: SELECT * FROM products WHERE id = '3' for update;
SELECT * FROM products WHERE id = '3' and type = 1 for update;
Example 2: (specify a primary key. If no data is found, no lock is required)
Copy the Code as follows: SELECT * FROM products WHERE id = '-1' for update;
Example 3: (no primary key, table lock)
Copy the Code as follows: SELECT * FROM products WHERE name = 'mouse 'for update;
Example 4: (the primary key is not clear, table lock)
Copy the Code as follows: SELECT * FROM products WHERE id <> '3' for update;
Example 5: (the primary key is not clear, table lock)
Copy the Code as follows: SELECT * FROM products WHERE id LIKE '3' for update;
NOTE 1: for update only applies to InnoDB and must be in the transaction block (BEGIN/COMMIT.
NOTE 2: To test the locking status, you can use the Command Mode of MySQL to open two windows for testing.
In MySql 5.0, the test is true.
In addition, MyAsim only supports table-level locks and InnerDB supports row-level locks.
Data that has been added (Row-Level Lock/table-Level Lock) locks cannot be locked by other transactions or be modified (modified or deleted) by other transactions)
The table is locked no matter whether or not records are queried.
In addition, if both A and B query the table id but cannot query the records, A and B do not apply the row lock in the query, but both A and B obtain the exclusive lock, at this time, if A inserts another record, it will be in the waiting state because B has A lock. If B inserts another record with the same data, it will throw the Deadlock found when trying to get lock; try restarting transaction and release the lock. At this time, A gets the lock and inserts it successfully.