Repeating transactions after a deadlock in InnoDB

怎甘沉沦 提交于 2019-12-24 05:10:10

问题


I'm a little confused on how to handle deadlocks in innodb. Here's acommon scenario i've found online:

while (some deadlock condition)
{
    try {
        begin transaction
        query 1
        query 2 // let's assume this one failed with a deadlock
        ...
        query N
        commit
    }
    catch {
        make sure it's a deadlock AND
        rollback
    }   
}
  • Question 1: So assuming query 2 fails, shouldn't i simply reapeat that query instead of rolling back the entire transaction and only roll back after X attempts?
  • Question 2: Could a simple select without any additional isolation instructions (i.e. SELECT * FROM table WHERE smth=smth) ever get into a deadlock?

回答1:


Answer 1:

A transaction deadlock causes InnoDB to roll back the entire transaction. Retry the whole transaction when this happens.

Answer 2:

No if the transaction isolation level is lower than SERIALIZABLE (or if run outside of a transaction):

SELECT ... FROM is a consistent read, reading a snapshot of the database and setting no locks unless the transaction isolation level is set to SERIALIZABLE.

Yes if SERIALIZABLE:

For SERIALIZABLE level, the search sets shared next-key locks on the index records it encounters.

Remember that

Normally, you must write your applications so that they are always prepared to re-issue a transaction if it gets rolled back because of a deadlock.

A SELECT may also just time-out, waiting for a lock from another transaction (e.g. a table-lock).



来源:https://stackoverflow.com/questions/19700388/repeating-transactions-after-a-deadlock-in-innodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!