This content has been marked as final. Show 4 replies
Normally, the lifecycle of an EntityManager (EM) is bound by a "logical" transaction (a unit or work). A long logical transaction may span several database transactions. EM acts as a session cache for entities it operates on. It seems that your "service" classes drive the logical transactions. Probably a method in your service class is mapped to one logical transaction or a unit of work. In such a case I'd keep my DAO stateless by having its methods take the EM as an argument instead of making the EM a member variable or creating it afresh in each DAO method. Passing EM as argument to DAO methods will ensure thread safety and also minimize the overhead incurred in creating and throwing away the EM (i.e. the cached entities in a session) in every DAO method.
This link may be of help too: [https://blueprints.dev.java.net/bpcatalog/ee5/persistence/webonlyapp.html|https://blueprints.dev.java.net/bpcatalog/ee5/persistence/webonlyapp.html]
Injecting EM into a stateless session EJB won't make the EM (or operations using it) thread safe. The point is that if your EM ends up as an instance variable (i.e. object state) of a class (your service class or a stateless session EJB) then thread safety of the containing class is not guaranteed.
In a normal Java program, I'd not keep a thread-unsafe object as a member variable of a class (otherwise I'll have to synchronize access to that thread-unsafe object).