JAVA: an EntityManager object in a multithread environment

user1589188 picture user1589188 · Feb 15, 2013 · Viewed 31.3k times · Source

if I have multiple threads, each use injector to get the EntityManager object, each use the em object to select a list of other class objects. Ready to be used in a for loop.

If a thread finishes first and calls clear(), will that affect the other threads? Like the for loop will have exception?

How about close()?

If the answer is "It depends", what (class definition? method call?) and where (java code? annotation? xml?) should I look at to find out how is it depended?

I did not write the source, I am just using someone else's library without documentation.

Thank you.

Answer

Makky picture Makky · Sep 9, 2013

Here is full working thread-safe Entity Manager Helper.

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerHelper {

    private static final EntityManagerFactory emf;
    private static final ThreadLocal<EntityManager> threadLocal;

    static {
        emf = Persistence.createEntityManagerFactory("Persistent_Name");
        threadLocal = new ThreadLocal<EntityManager>();
    }

    public static EntityManager getEntityManager() {
        EntityManager em = threadLocal.get();

        if (em == null) {
            em = emf.createEntityManager();
            // set your flush mode here
            threadLocal.set(em);
        }
        return em;
    }

    public static void closeEntityManager() {
        EntityManager em = threadLocal.get();
        if (em != null) {
            em.close();
            threadLocal.set(null);
        }
    }

    public static void closeEntityManagerFactory() {
        emf.close();
    }

    public static void beginTransaction() {
        getEntityManager().getTransaction().begin();
    }

    public static void rollback() {
        getEntityManager().getTransaction().rollback();
    }

    public static void commit() {
        getEntityManager().getTransaction().commit();
    }
}