2

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.

1 Answer 1

1

In a single node application you could try to lock objects in Session (Pessimistic versioning) when retrieving them from DB.

More on locking. And a bit of advice on hibernate concurrency.

But maybe you should rethink you units of work. Adding locking or synchronized blocks will add a high contention on your application. It is best to bear in mind when you develop a bit of transaction basics. Shortening life span of objects or an Detached Object pattern. Using Optimistic versioning (by adding a version field for example) and then processing errors on concurrent modifications.

Sign up to request clarification or add additional context in comments.

1 Comment

Actually, the instance objects that I try to update live in memory in the application life time. Different services update different fields of the entities. And when an update occurs it is written to the DB through the merge operation as above. I think I should look at the links you provided to have an insight, thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.