Optimistic v/s Pessimistic Locks
Why do we need locks ?
To put this in the most simplistic terms — Locks are mechanism used to ensure data integrity.
A database lock is used to “lock” some record in a database so that only one database user or session can update that particular data. So, database locks exist to prevent two or more database users from updating the same exact piece of data at the same exact time.
There are different levels of locks that can be acquired:-
- A single row
- A single page
- A table as a whole
- An entire database
Pessimistic Lock
Pessimistic Locking is when you lock the record for your exclusive use until you have finished using it. It has much better integrity than optimistic locking but requires you to be careful with your application design to avoid Deadlocks.
The disadvantage is that resource is locked from when you start the transaction until you finished the transaction. During that time the record is not available to other transactions.
Optimistic Lock
Optimistic Locking is a when you read a record, take note of a version number and check that the version hasn’t changed before you write the record back. When you write the record back you filter the update on the version to make sure it’s atomic.
Other transactions are able to concurrently access to the resource and the possibility of conflicting changes is possible. At commit time, when the resource is about to be updated in persistent storage, the state of the resource is read from storage again and compared to the state that was saved when the resource was first accessed in the transaction. If the two states differ, a conflicting update was made, and the transaction will be rolled back.
Thanks for reading
Happy Coding!!