Member-only story
Pessimistic Lock in Spring Boot
In this tutorial, we will learn What is Pessimistic lock ? What are the benefits of using pessimistic locks? How to apply pessimistic lock in spring boot application?
There are plenty of situations when we want to retrieve data from a database. Sometimes we want to lock it for ourselves for further processing so no one else can interrupt our actions.
A pessimistic lock is a concurrency control mechanism used in database systems. We can use a pessimistic lock to ensure that no other transactions can modify or delete reserved data.
JPA specification defines three pessimistic lock modes but here we’re going to discuss PESSIMISTIC_WRITE lock:
PESSIMISTIC_WRITE : Any transaction that needs to acquire a lock on data and make changes to it should obtain the PESSIMISTIC_WRITE lock. According to the JPA specification, holding PESSIMISTIC_WRITE lock will prevent other transactions from reading, updating or deleting the data..
What are the benefits of using pessimistic locks ?
Rollbacks can be costly for the database system as it needs to revert all current pending changes which might involve both table rows and index records. For this reason, pessimistic locking might be more suitable when conflicts happen frequently, as it reduces the chance of rolling back transactions.