3 Replies Latest reply on Dec 13, 2010 9:59 PM by Kieran Simpson

    Why do EJBs share EntityManager instances

    Kieran Simpson Newbie

      In the application I am developing, the input comes from a Seam UI, where messages are placed onto a JMS queue to be processed asynchronously.  Since multiple users can use the UI concurrently, multiple messages can be processed concurrently by the backends MDB/EJBs.


      The DAO layer is comprised of a Stateless Session Bean with the EntityManager being injected via the @PersistenceContext annotation.  When a message is polled from the queue and processed, the top level EJB coordinator for the processing starts a new transaction via the REQUIRES_NEW TransactionAttributeType.  However when one thread encounters a DB error, the shared EntityManager rolls back all transactions, thus the other threads fail.  I've done a heap dump analysis with Visual VM and I can see that my DAO instances all are being injected with the one instance of TransactionScopedEntityManager.


      Reading the Hibernate docs, the EntityManager is not thread safe.  Doing a lot of Googling I'm seeing a lot of other forum posts on this subject, however a lot of the material is years old and thus could be outdated.


      Why doesn't JBoss do a similar SharedEntityManager idea like that of Spring, or OC4J?  Surely it would be a good idea to have code abstracting away the threading concerns of EntityManagers by injecting a wrapper that is thread safe, and that delegates to underlying Hibernate EntityManagers.