In my application two thread try to update the same entity in a code as follows:
public static <T> T updateEntity(T entity, long id) {
long start = System.currentTimeMillis();
EntityManager em = null;
EntityTransaction tx = null;
try {
em = GenericPersistenceManager.emf.createEntityManager();
tx = em.getTransaction();
tx.begin();
entity = em.merge(entity);
tx.commit();
LoggerMultiplexer.logDBAccess(start, System.currentTimeMillis(),
String.format(OPERATION_UPDATE_ENTITY, entity.getClass().getName(), id));
return entity;
}
...
Sometimes, I get a duplicate key error in the commit line. I guess this occurs when the threads try to update the entity at the same time. Is it possible? I think so, because if I add a synchronized to the function above, I don't get the duplicate key exception. So, do I have to consider such kind of concurrency issues? If so, what would be the proper way, if I have multiple threads trying to update the same object.