I am using Hibernate, trying to simulate 2 concurrent update to the same row in database.
Edit: I moved em1.getTransaction().commit to be right after em1.flush(); I am n
Well, you're trying to get into a deadlock and you're succeeding :-)
Real life simulation would have 1st and 2nd entity manager plus appropriate updates / transactions in separate threads. That way you'd have:
Note that at that point (#4 above) you'd be overwriting changes made by Transaction1. Hibernate can use optimistic locking as well as pessimistic locking to prevent that from happening.
Update (based on comment):
If the entity is versioned, Transaction2 (#4 above) will fail. However, your code as posted does not get to that point because Transaction2 can't obtain the lock as explained above. If you want to specifically test that optimistic version control is working you can do the following: