These are the two code snippets given in EJB 3 in Action on page 448 and page 449:
//--- Do NOT do this!!! This is not recommended!!! public class ActionBazaarBidControllerServlet extends HttpServlet{ @PersistenceContext(unitName="actionBazaar") private EntityManager entityManager; }
and
@PersistenceContext(name="actionBazaar/EntityManager", unitName="actionBazaar") public class ActionBazaarBidControllerServlet extends HttpServlet{ private EntityManager entityManager; }
I am not able to understand how these two are different. I know that the Servlet is a multi threaded environment and EntityManager is not thread safe, but how is the 2nd code snippet any different from the first one?
In the first example you are injecting the PersistenceContext into your servlet's entityManager instance variable.
In the second one, you are registering into the JNDI ENC a reference to the PersistenceContext under the "actionBazaar/EntityManager" name. That registration is done for your servlet's ENC registry only. Your servlet may now do a JNDI lookup of the PersistenceContext using that name.
The second example is doing a JNDI registration while the first one is injecting the PersistenceContext into a member variable of your servlet.
I agree with Sergio. The second example is lacking the JNDI lookup. There is the same explanation somewhere in another chapter of the book. I don't have the book under hands now, so I can't tell you which page it is. Look for a gray background enclosed note in a former chapter.
Ok. I can understand that guys, but now my question is, does doing a JNDI lookup in the second code snippet make the EntityManager thread safe? Doesn't it too have the same disadvantages as a injection has?
Originally posted by nitin pai: Ok. I can understand that guys, but now my question is, does doing a JNDI lookup in the second code snippet make the EntityManager thread safe?
It does. The lookup is done inside your servlet's service method: once for each thread. That means, each thread will have its own PersistenceContext instance.
In the other hand, when you inject the PersitenceContext into your servlet's member variable you'll end with only one PersistenceContext instance for all the threads your servlet's service method runs on. It is in that kind of scenarios that race conditions may arise.