我正在尝试调查我的应用程序中的死锁问题。我的桌子看起来像这样。
CREATE TABLE `requests` (
`req_id` bigint(20) NOT NULL auto_increment,
`status` varchar(255) default NULL,
`process_id` varchar(200) default NULL,
PRIMARY KEY (`req_id`),
KEY `status_idx` USING BTREE (`status`),
KEY `pk_idx_requests` USING BTREE (`req_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8
- 服务(多线程)在此表上发出插入语句。
多个客户端在两个单独的事务中按顺序发出以下查询。
update requests set process_id='" + hostName + "' where status='Received' and process_id is null order by req_id asc limit 100"
select * from requests where process_id='"+ hostName + "' where status='Received';
更新请求 set status='Processing' where req_id='xyz'
第三个查询中的 Req_id 是从第二个查询中检索到的请求 ID 列表。
但有时在客户端,我们会看到以下异常。
Deadlock found when trying to get lock; try restarting transaction
org.hibernate.exception.LockAcquisitionException: could not execute native bulk manipulation query
上述查询是否会导致死锁,如果是,我们该如何解决?还有没有办法在本地重现这个问题?
这是“显示 innodb 状态”的输出
LATEST DETECTED DEADLOCK
------------------------
120507 6:03:21
*** (1) TRANSACTION:
TRANSACTION 115627, ACTIVE 1 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 3 lock struct(s), heap size 1248, 25 row lock(s)
MySQL thread id 432399, OS thread handle 0x419e4940, query id 4111695 * * * Searching rows for update
update requests set process_id='**' where status='Received' and process_id is null order by req_id asc limit 100
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 4 page no 3797 n bits 136 index `PRIMARY` of table `db`.`requests` trx id 115627 lock_mode X locks rec but not gap waiting
Record lock, heap no 67 PHYSICAL RECORD: n_fields 27; compact format; info bits 0
*** (2) TRANSACTION:
TRANSACTION 115626, ACTIVE 1 sec updating or deleting
mysql tables in use 1, locked 1
3 lock struct(s), heap size 1248, 2 row lock(s), undo log entries 1
MySQL thread id 432403, OS thread handle 0x41c19940, query id 4111694 * * * Updating
update requests set status='Processing', process_id='**' where req_id=3026296
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 4 page no 3797 n bits 136 index `PRIMARY` of table `db`.`requests` trx id 115626 lock_mode X locks rec but not gap
Record lock, heap no 67 PHYSICAL RECORD: n_fields 27; compact format; info bits 0