I am learning JPA pessimistic lock. I found the following explanation
PESSIMISTIC_READ - The Entity is locked on the database, prevents any other transaction from acquiring a PESSIMISTIC_WRITE lock.
PESSIMISTIC_WRITE - The Entity is locked on the database, prevents any other transaction from acquiring a PESSIMISTIC_READ or PESSIMISTIC_WRITE lock.
If I understand it right, then if we have three users (A, B, C) and user A gets READ lock, then user B can get READ lock too, but user C can't get WRITE lock until users A and B releases their locks. And if user A gets a WRITE lock then user B and user C can't get nothing until user A releases the lock.
However, for my client-server application I want the following logic. If users want only to read an entity their open the entity in READ-ONLY mode (unlimited number of users can do it at the same time). If some user wants to edit the entity he opens it in WRITE mode - no one can open the same entity in WRITE mode (until the user releases the WRITE lock) but all other can still open the entity in READ-ONLY mode.
And I have two questions:
Is my understanding of JPA pessimistic lock right?
Yes, that's exactly how read/write locking works
...but all other can still open the entity in READ-ONLY mode
I'm not exactly sure what you mean. We are still talking about multiple transactions executing simultaneously, right (I have a strange feeling that's not what you mean)? If that's the case, then in your logic, holding a 'READ_ONLY' lock accomplishes nothing.
Locking means 'I'm freezing this resource so that certain other transactions cannot proceed until I'm done'. But, in the logic you described, when you're holding the 'READ_ONLY' lock, both a transaction holding the 'READ_ONLY' lock and the transaction holding the 'WRITE' lock are allowed to proceed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.