我理解乐观锁定和悲观锁定之间的区别。现在,谁能给我解释一下,我一般什么时候使用这两种方法?
这个问题的答案是否会随着我是否使用存储过程来执行查询而变化?
但是为了检查一下,乐观的意思是“阅读时不要锁定表”,而悲观的意思是“阅读时锁定表”。
我理解乐观锁定和悲观锁定之间的区别。现在,谁能给我解释一下,我一般什么时候使用这两种方法?
这个问题的答案是否会随着我是否使用存储过程来执行查询而变化?
但是为了检查一下,乐观的意思是“阅读时不要锁定表”,而悲观的意思是“阅读时锁定表”。
当前回答
在大多数情况下,乐观锁定的效率更高,性能也更高。在悲观锁定和乐观锁定之间进行选择时,请考虑以下因素:
Pessimistic locking is useful if there are a lot of updates and relatively high chances of users trying to update data at the same time. For example, if each operation can update a large number of records at a time (the bank might add interest earnings to every account at the end of each month), and two applications are running such operations at the same time, they will have conflicts. Pessimistic locking is also more appropriate in applications that contain small tables that are frequently updated. In the case of these so-called hotspots, conflicts are so probable that optimistic locking wastes effort in rolling back conflicting transactions. Optimistic locking is useful if the possibility for conflicts is very low – there are many records but relatively few users, or very few updates and mostly read-type operations.
其他回答
在大多数情况下,乐观锁定的效率更高,性能也更高。在悲观锁定和乐观锁定之间进行选择时,请考虑以下因素:
Pessimistic locking is useful if there are a lot of updates and relatively high chances of users trying to update data at the same time. For example, if each operation can update a large number of records at a time (the bank might add interest earnings to every account at the end of each month), and two applications are running such operations at the same time, they will have conflicts. Pessimistic locking is also more appropriate in applications that contain small tables that are frequently updated. In the case of these so-called hotspots, conflicts are so probable that optimistic locking wastes effort in rolling back conflicting transactions. Optimistic locking is useful if the possibility for conflicts is very low – there are many records but relatively few users, or very few updates and mostly read-type operations.
关于乐观锁定和悲观锁定,上面已经说了很多好的东西。 需要考虑的一个重要问题如下:
在使用乐观锁定时,我们需要注意应用程序如何从这些故障中恢复。
特别是在异步消息驱动的体系结构中,这可能导致消息处理无序或更新丢失。
需要仔细考虑失败场景。
乐观锁定和悲观锁定是数据库中锁定数据的两种模型。
乐观锁定:仅在向数据库提交更改时才锁定记录。
悲观锁定:在编辑记录时锁定记录。
注意:在两种数据锁定模型中,锁都是在将更改提交给数据库后释放的。
乐观锁定用于不期望发生太多冲突的情况。进行正常操作的成本较低,但如果碰撞确实发生,您将支付更高的代价来解决它,因为交易被中止。
悲观锁定在预期发生碰撞时使用。会违反同步的事务被简单地阻塞。
为了选择合适的锁定机制,您必须估计读取和写入的量并相应地进行计划。
乐观假设你读的时候什么都不会改变。
悲观的人认为某件事会发生,所以锁定它。
如果数据被完全读取不是必要的,请使用乐观。你可能会得到奇怪的“肮脏”解读——但它不太可能导致死锁或类似的情况。
大多数web应用程序都可以接受脏读——在极少数情况下,下一次重新加载时数据不完全一致。
对于精确的数据操作(如在许多金融交易中)使用悲观。准确读取数据非常重要,没有未显示的更改——额外的锁定开销是值得的。
对了,Microsoft SQL server默认为页面锁定——基本上就是你正在读的那一行和两边的几行。行锁定更准确,但速度要慢得多。通常值得将事务设置为读提交或无锁,以避免读取时发生死锁。