How to avoid database deadlocks?

后端 未结 2 1957
抹茶落季
抹茶落季 2021-01-13 22:19

Some database features, such as SELECT ... FOR UPDATE and ON DELETE CASCADE, are implicitly vulnerable to deadlocks because the database does not s

相关标签:
2条回答
  • 2021-01-13 23:00

    A few years wiser, I am revising the accepted answer to state that database deadlocks cannot be prevented.

    If you are lucky enough to be able to break down database operations to only interact with a single table at a time (something that isn't always possible) then you are forced to choose between poor performance and the possibility of deadlocks. Pick your poison.

    0 讨论(0)
  • 2021-01-13 23:13

    Just don't use those features which can cause deadlocks. ON DELETE CASCADE can be re-written in a way that forces an order and thus avoids deadlocks.

    SELECT ... FOR UPDATE is specifically designed to allow you to avoid locks -- it lets you select and lock a row so you can keep a consistent order on all threads.

    You do have to be careful how you use it, it could cause a deadlock if you don't understand the locking order of all your updates.

    0 讨论(0)
提交回复
热议问题