I have the following scenario:
Thread 1 creates 'Job' objects, saves them to the db and puts them in a queue to process.
Thread 2 grabs the objects from the queue processes them and then saves them to the db with a 'completed' status.
The problem i'm having is that every once in a while i get
Code:
javax.persistence.OptimisticLockException
...
Could not synchronize database state with session
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)
This happens every once in a while at random times, and so far i have not been able to reproduce it in a controlled environment.
I can tell you that the "unsaved-value mapping was incorrect" is not the reason for this. The mappings are fine and the objects are actually saved fine despite the exception. So right now i just ignore the exception and keep going.
I should mention that the 'job processing' is actually very fast (a few millis), so Thread 2 will re-save the job very shortly after Thread 1 first saves it.
Both threads also flush the session after saving the job. My initial thought was that Thread 2 was re-saving the job before Thread 1 had finished saving it, but shouldn't flushing the session prevent this?
I am using the HibernateEntityManager interface to hibernate and version 3.2.6
This obviously has to do with the threads stepping on each-other's toes, so my question is what is the best way to handle this type of scenario?
Thanks