Hibernate JPA - PESSIMISTIC_WRITE, read the locked record

Viewed 191

I was reading this article https://www.baeldung.com/jpa-pessimistic-locking, where it's written that

PESSIMISTIC_WRITE – allows us to obtain an exclusive lock and prevent the data from being read, updated, or deleted

So I tried to confirm this.

In Transaction(TX1), I took a PESSIMISTIC_WRITE lock on an entity1. Then called a Thread.sleep(5). While TX1 is going on, I did a GET API call on the same entity1, which returned the data with 200 status. After which TX1 got completed. Maybe my implementation is wrong here, Could anyone help me in understanding this?

Resources used: JAVA 8, Mysql version: 5.6.34, Engine: InnoDB

If I'm able to read a locked entity, then this may lead to a dirty update. So in TX2, I did a plain findById and then did an update on entity1. Here TX2 is waiting till TX1 is completed because of locking but TX2 will do a dirty update as it is not aware of the changes made by TX1.

0 Answers
Related