Pessimistic Offline Lock prevents conflicts between concurrent business transactions by allowing only one business transaction at a time to access a particular data object. Example: If Joe edits the record of Customer X, Bill can not get access to edit the record of Customer X until Joe has committed his changes.
Ruby on Rails
Ruby on Rails provides several mechanisms to handle the locking of objects to ensure data consistency and prevent race conditions when multiple processes or users attempt to edit the same object simultaneously. The two primary types of locking mechanisms in Rails are Optimistic Locking and Pessimistic Locking.
Pessimistic Locking is a technique where a record is locked for the duration of a transaction, preventing other processes from modifying it until the lock is released. This is typically done using database-level locks.
How It Works:
- Use lock method to lock the record.
- The lock is held until the end of the transaction.
Example: Usage: Use the lock method within a transaction to lock the record.
ActiveRecord::Base.transaction do
article = Article.lock.find(1)
article.title = "New Title"
article.save
end
The lock
method issues a SELECT ... FOR UPDATE SQL
query, which locks the selected rows until the transaction is complete.
Summary
- Optimistic Locking: Uses a
lock_version
column to detect conflicts and raise an error if a record has been modified by another process since it was last read. It is suitable for scenarios where conflicts are rare. - Pessimistic Locking: Locks a record for the duration of a transaction, preventing other processes from modifying it until the lock is released. It is suitable for scenarios where conflicts are likely and need to be prevented.
Both mechanisms help ensure data consistency and prevent race conditions when multiple processes or users attempt to edit the same object simultaneously.