使用乐观锁定时会出现死锁吗? [英] Could there be a deadlock when using optimistic locking?

查看:694
本文介绍了使用乐观锁定时会出现死锁吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,有两种锁定策略:乐观锁定与悲观锁定

As is known, there are two locking strategy: Optimistic vs. Pessimistic locking

悲观锁定是指您锁定记录以供独占使用时 直到完成为止.它的完整性比 乐观锁定,但要求您小心 避免死锁的应用程序设计.

Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks.

同样,乐观并发控制乐观与多版本并发控制-区别?

Also knonw, that Optimistic Concurrency Control is not the same as Multi Version Concurrency Control (Oracle or MSSQL-Snapshot/MVCC-RC): Optimistic vs Multi Version Concurrency Control - Differences?

但是如果在两个交易中都使用OCC(乐观并发控制),则可能会在两个交易之间发生死锁?

But can occur deadlock between two transactions if used OCC(Optimistic Concurrency Control) in both?

我们可以说乐观锁定通过降低一致性来减少死锁的可能性吗?而且,只有在每次更新都在单独的事务中时,死锁的可能性才是0%,但一致性最小.

Can we say that the optimistic locking reduces the likelihood of deadlock by reducing the consistency? And only if each update is in a separate transaction, then the likelihood of deadlock is 0%, but with this the smallest consistency.

推荐答案

可以.

死锁只是意味着线程A持有线程B正在等待的锁,而B持有线程A正在等待的锁.如果您的应用程序并非设计为在任何地方都以相同的顺序锁定资源,则无论采用何种锁定策略,死锁都非常容易.

A deadlock simply means that thread A holds a lock that thread B is waiting on while B holds a lock that A is waiting on. If your application is not designed to lock resources in the same order everywhere, it's easy enough to deadlock regardless of your locking strategy.

想象一下,线程A和B都想更新父表和子表中的特定行.线程A首先更新父行.线程B首先更新子行.现在,线程A尝试更新子行并发现自己被B阻止.同时,线程B尝试更新父行并发现自己被A阻止.您有一个死锁.

Imagine that threads A and B both want to update a particular row in a parent table and in a child table. Thread A updates the parent row first. Thread B updates the child row first. Now thread A tries to update the child row and finds itself blocked by B. Meanwhile, thread B tries to update the parent and finds itself blocked by A. You have a deadlock.

如果您在Oracle中具有一致的锁定资源顺序(即始终在孩子之前锁定父级),则无论您采用哪种锁定策略,都不会出现死锁.通常,在SQL Server中不会出现死锁,但是在SQL Server中升级行级锁的可能性使这种不确定性降低.

If you had a consistent order for locking resources (i.e. always lock the parent before the child) in Oracle you won't get deadlocks regardless of your locking strategy. You generally won't get deadlocks in SQL Server but the potential for row-level locks to get escalated in SQL Server makes that less than certain.

这篇关于使用乐观锁定时会出现死锁吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆