Optimistic vs. Pessimistic locking

前端 未结 10 1047
庸人自扰
庸人自扰 2020-11-21 22:35

I understand the differences between optimistic and pessimistic locking. Now could someone explain to me when I would use either one in general?

And does the answer

10条回答
  •  独厮守ぢ
    2020-11-21 23:25

    Optimistic assumes that nothing's going to change while you're reading it.

    Pessimistic assumes that something will and so locks it.

    If it's not essential that the data is perfectly read use optimistic. You might get the odd 'dirty' read - but it's far less likely to result in deadlocks and the like.

    Most web applications are fine with dirty reads - on the rare occasion the data doesn't exactly tally the next reload does.

    For exact data operations (like in many financial transactions) use pessimistic. It's essential that the data is accurately read, with no un-shown changes - the extra locking overhead is worth it.

    Oh, and Microsoft SQL server defaults to page locking - basically the row you're reading and a few either side. Row locking is more accurate but much slower. It's often worth setting your transactions to read-committed or no-lock to avoid deadlocks while reading.

提交回复
热议问题