4 Replies Latest reply on Feb 14, 2011 3:33 AM by jaikiran pai

    servlet EntityManager Injection and thread-safe

    Thunder Lei Newbie

      Hi,

       

      There are may discussions about how to inject an EntityManger into servlet and thread-safe issue.

      After I go through some the discussions, I get my own conclusion,  there are three manners to inject an EntityManger into servlet.

       

      1. direct injection

      In servlet class, using @PersistenceContext(unitName="myPersistenceUnit") private EntityManager entityManager;

      @PersistenceContext(unitName="myPersistenceUnit")
      private EntityManager entityManager;

      to inject entity manager to instance variable.

       

      2. registering the JNDI ENC, a reference to the PersistenceContext

      @PersistenceContext(name="sample/EntityManager", unitName="myPersistenceUnit")

      public class TestEntityManagerThreadServlet1 extends HttpServlet {

      And you lookup the Enitymamger in for every request in servlet methods such doPost, doGet, servive....

      DO NOT save the Entitynamger instance with class variable in the servlet.

       

      3. inject EntitymangerFactory

      You can inject an EntitymangerFactory into a instance variable of servlet.

      And you create Entitymanager from EntitymangerFactory for every request to the servlet.

       

      As my understanding, in the above three way, the fist one is NOT thread-safe and last two are.

      But when I create a small web application to verify the conclusion, that's NOT it.

      The problem is that in the second situation, when I lookup the Entitymamger via the JNDI ENC, I always get the same Entitymanager instance even if for concurrent request to the web application.

      So to me, seems only the last one is thread-safe.

       

      Is there anything wrong with my testing?

      Can you guys give some advice or direction on this?

       

      Thanks,

      Thunder