近来程序员用java多线程导入数据经常遇到死锁,下面简单模拟死锁的成因
update
SES1: update t set a=1 where id=1;
SES2: update t set a=2 where id=2;
SES1: update t set a=2 where id=2;(挂住,等待SES2提交或者回滚)
SES2: update t set a=1 where id=1;(挂住,等待SES1提交或者回滚,此时SES1和SES2互相等待,形成死锁)
delete
SES1: delete from t where id=1;
SES2: delete from t where id=2;
SES1: delete from t where id=2;(挂住,等待SES2提交或者回滚)
SES2: delete from t where id=1;(挂住,等待SES1提交或者回滚,此时SES1和SES2互相等待,形成死锁)
insert(insert引起死锁一般是因为某些约束引起的,我们假设在t的id列有唯一性约束)
SES1: insert into t(id) values(1);
SES2: insert into t(id) values(2);
SES1: insert into t(id) values(2);(挂住,等待SES2提交或者回滚)
SES2: insert into t(id) values(1);(挂住,等待SES1提交或者回滚,此时SES1和SES2互相等待,形成死锁)
以上都是模拟引起死锁的最简单的情况,实际中,引起死锁的语句可能是由UPDATE、DELETE、INSERT混合而成。约束会增大UPDATE和INSERT引起死锁的可能性,外建上没有索引会增大所有DML引起是死锁的可能性。