Short Definition: Pessimistic Locking vs Optimistic Locking

In Pessimistic Locking a lock is always applied to a modifiable resource once it is accessed in an — even potentially — modifiable transaction. A lock prevents other requests from modifying the resource as the current transaction proceeds. This is necessary to prevent other requests from modifying a resource whereas the current transaction assumes a certain state that is not given anymore as the resource has already been modified by a faster processing operation. This is the core problem that can also be addressed in a different way. In Optimistic Locking, no lock is applied. Instead once a resource is accessed, its state is temporary saved. After the transaction has modified the resource and is about to commit the modified resource to persistent storage, the resource is read again from persistent storage and compared to the temporary saved state from the beginning of the transaction. If the retrieved state differs from the previously temporary saved state of the resource, then the resource has been modified by another operation in the meantime. In this case the current transaction needs to rollback.  

What is better? Depends… but usually you should choose Optimistic Locking as it’s better in multi-user resp. concurrency driven environments. 


Popular posts from this blog

Tuning ext4 for performance with emphasis on SSD usage

Eclipse sucks, so use NetBeans!