2

I am getting following exception when I try to do a batch update. There are multiple threads running at same time which might be accessing a row in database. I am doing multiple batch updates. Can anyone please comment on relation between size of batch and deadlock ? By decreasing the batch size (currently batch size = 1000), will the probability of deadlock decrease ?

The exception I am getting is

com.mysql.jdbc.exceptions.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction
4

1 Answer 1

2

Short answer:

yes, the probability would decrease

Long answer:

Lets figure out why the deadlocks are occurring. When you update a row an exclusive lock is set on this particular row and it will be held until your transaction is commited/rolled back. That means, no other transaction may update it — it would just block until the transaction is finished. A deadlock would occur when tran1 is willing to lock rows being held by tran2, and tran2, in turn, is already waiting for some rows locked by tran1

Here's an example:

MariaDB [test]> create table a (id int primary key, value int);
Query OK, 0 rows affected (0.14 sec)

MariaDB [test]> insert into a values (1, 0), (2, 0), (3, 0), (4, 0);
Query OK, 4 rows affected (0.00 sec)
Records: 4  Duplicates: 0  Warnings: 0

mysql console 1:
step 1> start transaction;
step 3> update a set value = 1 where id = 2;
step 5> update a set value = 1 where id = 1;

mysql console 2:
step 2> start transaction;
step 4> update a set value = 1 where id = 1;
step 6> update a set value = 1 where id = 2;

ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction

The more rows are being touched(=updated) during every batch update, the higher the probability of such kind of conflicts is.

You might lower this probability by traversing the rows in a well-defined order. In this case the simple example I've provided wouldn't be feasible. More details on avoiding deadlocks are in this awesome article: http://www.xaprb.com/blog/2006/08/03/a-little-known-way-to-cause-a-database-deadlock/

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.