Can you explain what pessimistic locking is and how it differs from optimistic locking?
sobes.tech AI
Answer from AI
Pessimistic locking is an approach to managing concurrent access to data, where it is assumed that conflicts will occur frequently. Therefore, a lock is placed on the resource immediately to prevent other operations from modifying it until the current transaction is completed.
Optimistic locking, on the other hand, assumes that conflicts are rare. It does not lock the resource when reading but checks before writing whether the resource has changed since it was read. If there are changes, the operation is rolled back or retried.
Example: in a database, pessimistic locking can be used through SQL queries with row locking (SELECT ... FOR UPDATE), while optimistic locking can be implemented through version fields or checksums.