MySQL并发insert因唯一键导致的DeadLock

        业务场景为:一个业务中向A表插入数据多条,同时向B表插入多条纪录,两张表都有组合唯一键,使用jmeter进行并发测试时出现死锁现象! <==== 一个业务同时向两张表中插入数据,同样的组合唯一索引,插入数据时锁表,并发量大必死锁!

        数据库和后台服务部署在同一机器上,单一线程操作的时候,同样的请求数据,A、B插入纪录的时间分别为5、4毫秒,几乎一样的时间消耗!

       AB表的唯一键是组合唯一键,插入数据时最前面的字段值一模一样,修改表结构后(去掉B表的唯一键限制),继续并发测试,没有死锁。

分析:

唯一键导致的全表锁?两个事务操作的线程:

trans1 拿到共享锁之后,等待trans 2的自增锁。

trans2 已经拿到了自增锁,要申请插入意向锁。(插入意向锁又等待trans1 的共享锁)产生了死锁。

 INSERT sets an exclusive lock on the inserted row. This lock is an index-record lock, not a next-key lock (that is, there is no gap lock) and does not prevent other sessions from inserting into the gap before the inserted row.
 
Prior to inserting the row, a type of gap lock called an insert intention gap lock is set. This lock signals the intent to insert in such a way that multiple transactions inserting into the same index gap need not wait for each other if they are not inserting at the same position within the gap. Suppose that there are index records with values of 4 and 7. Separate transactions that attempt to insert values of 5 and 6 each lock the gap between 4 and 7 with insert intention locks prior to obtaining the exclusive lock on the inserted row, but do not block each other because the rows are nonconflicting.
 
If a duplicate-key error occurs, a shared lock on the duplicate index record is set. This use of a shared lock can result in deadlock should there be multiple sessions trying to insert the same row if another session already has an exclusive lock. This can occur if another session deletes the row. Suppose that an InnoDB table t1 has the following structure:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值