I'm in the following situation.
There are several threads that can read/update MonthlySales
persistent objects. Problem is that these objects may not exist and have to be dynamically created upon request.
So, two different threads my end up creating the entity corresponding to the same key (i.e. having the same ID), thus one of them failing to commit. I don't want this to happen. I would like one of the two threads to win the race and the other one to loose, waiting until the object has been created by the other.
In other words, I do want to do serialized transactions. Should I put an explicit Java lock (i.e. synchronized
block)?
My current code is the following:
MonthlySales ms = entityManager.find(MonthlySales.class, somekey);
if (ms == null) { // two threads might enter this block altogether
ms = new MonthlySales();
// prepare ms object populating its fields with default values
entityManager.persist(ms);
entityManager.flush();
}
entityManager.lock(ms, LockModeType.PESSIMISTIC_WRITE); // lock this object
// since we are going to update it
// do something with ms object
entityManager.getTransaction().commit();
entityManager.close();
Can you help me?