Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question regarding Optimistic Locking

 
Bharat Bonde
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I want to use Optimistic Locking for concurrency control(As I am expecting may be 5-10 concurrent users).
I am using JPA which is using Hibernate as its persistence provider...
I want to let only one thread to update my entity while the other waits or may be try again...because I don't want to ignore any thread due to OptimisticLockException...
My question is:
What should be the course of action when I get an OptimisticLockException?
Should I catch the exception and in the catch block refresh the entity and try to acquire lock on it and then update it?If so, what happens if while inside the catch block another thread tries to acquire lock on it for update(will it cause another exception)?


Thanks in Advance.
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It depends on what you want. If you catch and retry, then it will always throw that exception because of what Hibernate is doing with Optimistic locking. It is sending an update statement with a where clause using your version field. So if update blah with blah Where version = 2, and version is already at 3 or higher, then that update statement will always update nothing and throw an Exception, it is what you want because you asked for Optimistic Locking.

If you want the second thread to automatically overwrite the data from the previous update, then you should choose a different path than optimistic locking.

But, for me what you should do it notify the user that they are trying to update stale data and to try again, by reloading the latest data and presenting it to the user to change again.

Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic