3

I am new to the EJB and hibernate, and the following confuses me because there seems to be contradiction whenever i search for the definite answer. Question:

Is it thread-safe to inject Entity manager directly into stateless bean in the following way?

@Stateless
public class SomeBean implements SomeInterface {

//..    
@Inject
private EntityManager entityManager;

//... non related transaction1()
//... non related transaction2()

Would each stateless bean have its own instance of EntityManager or shared instance could be injected?

According to Hibernate docs:

An EntityManager is an inexpensive, non-thread-safe object that should be used once, for a single business process, a single unit of work, and then discarded.

Does an EJB container make it thread safe?

And according to the EJB docs, stateless session beans are inherently thread safe by not allowing different clients operate on same bean at the same time.

However, I have read examples in which EntityManagerFactory should be injected instead of EntityManager and if EntityManager is injected directly it should be done in Stateful bean.

Would it be safe to always inject EJB directly into Stateless bean like shown above or what would be use case when it wouldn't work?

Tiny
  • 27,221
  • 105
  • 339
  • 599
John
  • 5,189
  • 2
  • 38
  • 62

1 Answers1

8

Would each stateless bean have its own instance of EntityManager or shared instance could be injected ?

None of both. The @Inject (and @PersistenceContext and @EJB) injects a proxy instance, not the actual instance.

The proxy will on every method call delegate to the right available instance in the current thread and context. In other words, the container worries about this all, not you.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • So, if there are 10 threads calling same transaction service, each will have its own entity manager ? – John Mar 14 '15 at 10:48
  • If there are 10 threads invoking a method on an injected `EntityManager`, then yes. – BalusC Mar 14 '15 at 10:49
  • 1
    @BalusC: What about injecting an EntityManager in a servlet? Is it still a thread-safe proxy used? – Mike Argyriou Jul 24 '15 at 13:46
  • 1
    @BalusC: But when the very same stateless bean with an instance variable entityManager is returned to the pool, then the state left over by the previous user will be seen/avaialable to use by the next user. Wouldn't it be? That just cannot be thread-safety. – Farhan stands with Palestine May 22 '16 at 11:26
  • 1
    @Shirgill: as answered, `@PersistenceContext` also injects a proxy. – BalusC May 22 '16 at 18:09