What's the difference between PESSIMISTIC_READ and PESSIMISTIC_WRITE in JPA?

Viewed 56727

I have read the article Locking and Concurrency in Java Persistence 2.0, and run the sample application. But I still can't realize the difference between PESSIMISTIC_READ and PESSIMISTIC_WRITE. I tried to modify the code, and where the code using PESSIMISTIC_READ and PESSIMISTIC_WRITE will have the same result that the SQL will invoked with for update.

5 Answers

This is probably going to be the least technical answer, so apologies if I get the semantics wrong. But I was frustrated with the complexity of the language in the previous answers, so I decided to post a simple answer:

  • PESSIMISTIC_READ: you obtain a lock on the record at the start of the transaction, for the purpose of reading only. Basically you're saying "I don't want anyone updating this record while I'm reading it, but I don't mind others reading it as well". That means people also attempting a PESSIMISTIC_READ will succeed, but those attempting a PESSIMISTIC_WRITE will fail

  • PESSIMISTIC_WRITE: you obtain a lock on the record at the start of the transaction, for the purpose of writing. What you're saying is "I'm going to be updating this record, so no one can read or write to it until I'm done". That means both those attempting a PESSIMISTIC_READ or PESSIMISTIC_WRITE will fail

the PESSIMISTIC part refers to the fact that you get the lock at the start of the transaction i.e. before making any changes to the record, rather than at the end of the transaction, when you are about to commit the changes to the record.

The PESSIMISTIC_READ acquires a shared (read) lock on the associated table row record, while the PESSIMISTIC_WRITE acquires an exclusive (write) lock.

The shared lock blocks any other concurrent exclusive lock requests, but it allows other shared lock requests to proceed.

The exclusive lock blocks both shared and exclusive lock requests.

What's worth mentioning is that, for Hibernate, if the database does not support shared locks (e.g. Oracle), then a shared lock request (e.g., PESSIMISTIC_READ) will simply acquire an exclusive lock request (e.g., PESSIMISTIC_WRITE).

Related