Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

What is optimistic locking vs. pessimistic locking?


Asked by Aubrey Schaefer on Dec 07, 2021 FAQ



The main difference is that optimistic locking incurs overhead only if there's a conflict , whereas pessimistic locking has reduced overhead on conflict. So optimistic is best in case where most transactions don't conflict - which I hope is usually the case for most apps.
Moreover,
If most transactions simply look at the resource and never change it, an exclusive lock may be overkill as it may cause lock contention, and optimistic locking may be a better approach. With pessimistic locking, locks are applied in a fail-safe way.
Next, In the majority of the cases, we would only need optimistic locking, thereby avoiding pessimistic locking at the most. We also gain performance by moving from an explicit (pessimistic) lock to an optimistic lock which checks the record at the time of an update instead of locking the record for the entire transaction.
Likewise,
There are two different approaches to transactional locking: Pessimistic locking and optimistic locking. The disadvantage of pessimistic locking is that a resource is locked from the time it is first accessed in a transaction until the transaction is finished, making it inaccessible to other transactions during that time.
One may also ask,
Optimistic locking where order has version number that is increased whenever the order or its order lines are changed Pessimistic locking on order lines table also possible, but row-level locking does not prevent adding new rows!