I'm quite new to JPA and read this article about locking modes in JPA2.0, which left me with a question regarding the LockModeType.OPTIMISTIC_FORCE_INCREMENT.
Here is an image with an example from the article: http://i.stack.imgur.com/dFjhZ.jpg
So far I understand that explicit optimistic locking in a transaction T1 is only necessary if my update to entity A depends on the state of another entity B that is just read.
I also understand that a lock using OPTIMISTIC_FORCE_INCREMENT causes B to update it's version attribute, which will lead to OptimisticLockException in all transactions that try to update B and have read it before the lock was issued (i.e. with the old version value).
My question is: What happens if another transaction T2 starts right after the version of B has been incremented, changes B and finishes before T1 commits?
As far as I understand T1 should get an OptimisticLockException. If so, what's the point of this lock, as it just slightly reduced the vulnerable time window of T1? This would mean that: if i want to be sure that B isn't changed until T1 finishes i need a pessimistic lock, right?
Thanks in advance for making this clear to me :)
Your example question highlights why this is called "OPTIMISTIC" locking. It's not perfect, but if suffices for a large number of situations in the real world AND it uses much less resources (including time) than a hard lock.
When using this type of locking, you're trading for performance, and often improved use-ability, betting that your transactions will just work the majority of the time, and you're assured that in those cases where it doesn't work you'll be notified (exception will be thrown) and you can then step back and "do the right thing": try again, abandon, ... however you choose to handle the exception.
The pessimistic lock may be very inappropriate for high-performance transactional system where you need some level of locking, but the probability of them colliding is minimal: how many of the millions of users of xTunes (name changed to protect the innocent..) "order" (update) at any moment, and how many are all ordering (updating) from the same account?