Hello everyone, 
In my application, I have some persistency objects (entity instances) which are loaded into memory and I use same instances throughout the lifecycle of the application. These objects can be modified by different threads and they are persisted into to the database with a code as follows:
Code:
    public static <T> T updateEntity(T entity, long id) {
        EntityManager em = null;
        EntityTransaction tx = null;
        try {
            em = GenericPersistenceManager.emf.createEntityManager();
            tx = em.getTransaction();
            tx.begin();
            entity = em.merge(entity);
            tx.commit();
            return entity;
            
        } catch (RuntimeException e) {
            if (tx.isActive()) {
                tx.rollback();
            }
            throw e;
        } finally {
            em.close();
        }
    }
Sometimes when two threads try to update same object I get an exception as follows:
Code:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1-6' for key 'PRIMARY'
I guess I'm getting this exception because of a concurrency issue. Because if I make the function abovesynchronized or if I run the threads one by one, I don't get the exception. So, what should I consider in this case? How can I handle this concurrency issue. I'm not so experienced in Hibernate. So, I will really appreciate your helps.
Thanks in advance