I was having similar problem. First of all you need to properly handle StaleStateException because it is going to happen a lot if your threads modify the same data.
When more than 2 threads check at the same if a record exist, they will get the same answer. If it does not exist they will both add the new entry. If you want to make sure that 2 thread cannot add the same data at the same time, you have to add in your model a "unique constrain" on some attributes of the class you want to persist. With a unique constrains, when a thread commit a transaction it will fail if another thread has already done it for the same unique identifier. This is another exception that needs to be taken care of.
Now to prevent that from happening, what you can do is carefully dispatch to threads information to be persisted in way that will avoid those conflicts.
When I get a StaleStateException or Constrain exception, what I do is rollback, clear and close the session, create a new Session and start over. With a well design dispatcher, it almost never happen.
|