deamon
deamon

Reputation: 92509

How is threadsafty guranteed with @PersistenceContext?

According to many examples it is possible to inject an EntityManager into @Stateless or @Singleton EJBs like this:

@Stateless // or @Singleton
public class MyRepository {
   @PersistenceContext
   private EntityManager em;
   ...
}

The EJB 3.1 Spec says that dependency injection is only performed at construction time, so that all callers of MyRepository would use the same instance of EntityManager. How does the EJB container ensure that the correct EntityManager instance is used?

Upvotes: 4

Views: 1317

Answers (1)

Mirko N.
Mirko N.

Reputation: 10567

My understanding is that a @Stateless bean will never be used by two clients concurrently; the container will simply create more instances of the same bean if it needs to serve multiple clients.

As for @Singleton beans, the spec says that by default they use Container Managed Concurrency, where the container uses method Locks and could reject clients with a timeout exception if the singleton is busy.

Edit: additionally, the @PersistentContext type is transaction-scoped by default (16.11.1.1 in the spec) so all entities managed by EntityManager are detached at the end of each transaction.

Upvotes: 3

Related Questions