A problem caused by Mysql gap lock

Sometimes, there will be some exceptions of mysql in our acquired log. The exception information is probably: Lock wait timeout exceeded try restarting transaction, or there are...gap... lights.

The reason for this is generally that the business logic in one thread needs to delete first and then insert; or two threads, one in delete and one in insert.

The key lies in the where condition of this delete. If the where condition is the primary key, the above problem will not occur.
If it is an ordinary index, there will be a possibility of this problem. This involves the gap lock problem. When the delete where statement has no records that meet the conditions, mysql will try to lock the index, the upper and lower positions of the where condition. Record. If you want to insert the record to another location at this time, this error will occur.

For example:
In t1, there are data
1, 2, 3, 7, 8.
Now the logic of the business method is:
delete from t1 where a=4;
insert t1 (a) values(5);
then an exception is thrown .

Because when delete where a=4, there are no records that meet the conditions in the table, mysql will lock the index in the range of 3 and 7, and then insert 5, which happens to fall in the range of 3 and 7, and also needs to get Only locks in the interval 3 and 7 will work, which will cause a deadlock.

Therefore, in the business method that needs to delete first and then insert, use the same condition to delete before delete, and then delete if there is data, otherwise, you can directly insert.



Guess you like

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