Database Lock
In other systems, database locks serve to protect shared resource or objects. These protected resource could be
- Table.
- Data rows.
- Data blocks.
A lock can be a read lock or write lock, is used when multiple users need to access a database concurrently. This prevents data from being corrupted or invalidated. This type of issues occur when multiple users try to read the or other users try to write the database.
Any single user can modify the database records , the items in the database to which they have applied a lock that gives them exclusive access to the record until the lock is released.
Pessimistic Locking
In pessimistic locking, a record or a page is locked immediately when the lock is requested.
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. To use pessimistic locking you need either a direct connection to the database (as would typically be the case in a two tier client server application) or an externally available transaction ID that can be used independently of the connection.
Optimistic Locking
- Begin - time stamp marking.
- Modify.
- Validate
- Commit/rollback
Optimistic Locking is a strategy where you read a record, take note of a version number (other methods to do this involve dates, timestamps or checksums/hashes) 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. (i.e. hasn't been updated between when you check the version and write the record to the disk) and update the version in one hit.
If the record is dirty (i.e. different version to yours) you abort the transaction and the user can re-start it or rollback.
Snapshots
A snapshot is a read-only static view of a database.
Hope this will help you to understand!