The problem has to do with thread safety on web applications. If you are using servlets, or a technology based on servlets like JSF, you must consider thread safety for persistence. A common injection is to use the container managed persistence context. This usually takes the following form
@PersistenceContext(unitName="myContext")
private EntityManager em;
The problem is this is NOT thread safe if used in a servlet. A servlet processes many requests and the container handles many requests. Even if you use an injection to get a UserTransaction, it lulls the programmer into a false sense of safety.
In their talk, they mentioned four methods to ensure thread safety on servlet based technologies
- Use a request-scoped bean Java Server Faces. The life of the bean is a single transaction.
- Use class level annotations with JNDI lookups
- Use a @Resource annotation
- Use the "old style" JNDI InitialContext lookup method
public EntityManager getEntityManager() throws NamingException {Another alternative is to use the @PersistenceUnit annotation to get an EntityManagerFactory. The EntityManagerFactory is a thread-safe object. From the factory we create the EntityManager. This is also thread-safe since it creates a new EntityManager per call.
Context ic = new InitialContext();
return (EntityManager) ic.lookup("java:comp/env/EM");
}
@PersistenceUnit(unitName="myContextPU")These methods should help the developer maintain thread-safety.
private EntityManagerFactory emf;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
No comments:
Post a Comment