美文网首页
Deadlock found when trying to...

Deadlock found when trying to...

作者: hbqzbl | 来源:发表于2021-04-05 19:50 被阅读0次

异常信息

Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction.

分析

死锁问题,两个事物互相等待以获取锁时,就会出现死锁问题,例如:

线程一:拥有A-----想拿B
线程二:拥有B-----想拿A

解决

mysql官方文档推荐的解决方案是当异常出现时增加尝试次数,比如按如下代码(java):

            //出现死锁情况  尝试三次
            int i = 0;
            while (true) {
                try {
                    //操作数据库
                    dao();
                    break;
                } catch (Exception e) {
                    i++;
                    if (i >= 4) {
                        logger.error("更新失败", e.getMessage());
                        throw e;
                    }

                    Thread.sleep(200);
                }
            }

另外,为了避免死锁,您必须确保并发事务不会按可能导致死锁的顺序更新行。一般来说,即使在不同的事务中,也要尝试始终以相同的顺序获取锁(例如,始终先获取表A,然后再获取表B),例如:

线程一:拥有A-----想拿B
线程二:拥有A-----想拿B

相关文章

网友评论

      本文标题:Deadlock found when trying to...

      本文链接:https://www.haomeiwen.com/subject/zfadkltx.html