Reputation: 1746
EntityManager
instantiated by myself is not thread-safe.EntityManager
injected via @PersistenceContext
in EJB behaves like hread-safe, because EJB container serializes access to EJB beans.EntityManager
is really a proxy.EntityManager
via @PersistenceContext
to @Dependent
CDI bean and inject that bean to EJB, it behaves like thread-safe because of covering EJB (I believe that in this case EntityManager
is proxy too).But:
EntityManager
via @PersistenceContext
to CDI bean and use this bean directly for example in Servlet? I believe that this EntityManager
is a proxy, so does this proxy guarantee thread safety?Edit: Similar question Java CDI @PersistenceContext and thread safety does't solve my problem, because accepted answer shows EJB examples, not CDI examples.
Edit: I checked source code of WildFly application server and it looks that WildFly uses thread-safe proxy in CDI. This proxy selects real EntityManager when needed. Real EntityManagers are kept in special structure - stack of maps of EntityManagers in ThreadLocal.
Upvotes: 2
Views: 672
Reputation: 815
The biggest benefit of using Transaction Scoped Entity Manager is that it is stateless. This also makes the Transaction Scoped EntityManager threadsafe and thus virtually maintenance free
also pro JPA book says:
a transaction-scoped entity manager is stateless, meaning that it can be safely stored on any Java EE component
Upvotes: 1