[转]一次Delete&Insert引发的Mysql死锁
近日遇到一个比较奇怪的deadlock错误, 错误详情:
Deadlock found when trying to get lock; try restarting transaction; nested exception is com.ibatis.common.jdbc.exception.NestedSQLException...
跟踪代码后最终定位到一段业务逻辑:
delete from A where no = $no;
insert into A(no, value) values($no, "value");
印象中mysql一直是使用行级锁, 为什么此处在并发时会发生死锁呢? 唯一的解释是mysql在这边锁住的不只一行数据.
简单搜索之后, 发现mysql的锁分为三种(按照锁定的行数划分):
1.record lock:记录锁,也就是仅仅锁着单独的一行
2.gap lock:区间锁,仅仅锁住一个区间(注意这里的区间都是开区间,也就 是不包括边界值,至于为什么这么定义?innodb官方定义的)
3.next-key lock:record lock+gap lock,所以next-key lock也就半开半闭区间,且是下界开,上界闭。(为什么这么定义?innodb官方定义的)
由于此处是在明确指定了no=XX的情况下抛出了死锁异常, 并且no建立的是普通索引, 所以此处mysql使用的应该是next-key lock(查看何种情况下使用何种锁 https://dev.mysql.com/doc/refman/5.7/en/innodb-locks-set.html).
下面来举个手册上的例子看看next-key lock是如何上锁的。假如一个索引的行有10,11,13,20
那么可能的next-key lock的包括:
(无穷小, 10]
(10,11]
(11,13]
(13,20]
(20, 无穷大)
下面分析何种情况下会发生死锁.
结合业务逻辑, 执行新增操作时也会执行一样的逻辑, 先进行delete.
例如,现在表student中有四条数据:
![](http://upload-images.jianshu.io/upload_images/1324594-b65f06d1e0bd8fc9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
现在要新增一条数据, no = 21, 这时候会先进行delete, 线程会锁住(20, 无穷大)这块区间, 加入这个时候另一个线程正在新增另一条数据 no = 22, 线程也会锁住(20, 无穷大)这块区间就会发生死锁.
下面看具体实验:
创建一张表student.
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`no` int(11) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `idx_no` (`no`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=latin1
插入数据:
INSERT INTO student (no,name) VALUES(10, "Jim");
INSERT INTO student (no,name) VALUES(11, "Kimi");
INSERT INTO student (no,name) VALUES(13, "Tom");
INSERT INTO student (no,name) VALUES(20, "Mike");
![](http://upload-images.jianshu.io/upload_images/1324594-f5ea3028d2b3cb03.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
执行两个事务:
session 1:
begin;
delete from student where no = 21;
session 2:
begin;
delete from student where no = 22;
此处解释一下, 此时,session 1和session 2都会对区间(20, 无穷大)加锁, 而区间锁只是用来防止其他事务在区间中插入数据,区间x锁 与区间S锁效果是一样的(只要不是插入操作), 因此两个session都会持有锁.
参考:https://dev.mysql.com/doc/refman/5.1/en/innodb-record-level-locks.html
Gap locks in InnoDB are “purely inhibitive”, which means they only stop other transactions from inserting to the gap. Thus, a gap X-lock has the same effect as a gap S-lock.
继续执行:
session 1:
INSERT INTO student (no,name) VALUES(21, "Zhoubing");
此时session 1阻塞(因为session 2持有区间锁), 如图:
![](http://upload-images.jianshu.io/upload_images/1324594-bea52a8da2c0415d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
session 2:
INSERT INTO student (no,name) VALUES(22, "Zhoubing");
此时session 2死锁(因为session 1持有区间锁), 如图:
![](http://upload-images.jianshu.io/upload_images/1324594-55b3d5b6be0e52dd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
.
总结, delete之后进行insert有可能发生死锁, 因为delete可能会持有区间锁, 而区间锁是可重入的(只要不是插入数据).
解决方案:
将事务隔离级别将为read commit.