How is threadsafty guranteed with @PersistenceContext?
Asked Answered
S

1

4

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?

Symmetrical answered 6/1, 2010 at 18:17 Comment(1)
Good question... I've often wondered about the nuts and bolts of thread safety in JEE5+ implementations.Euhemerus
P
3

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.

Papandreou answered 6/1, 2010 at 20:22 Comment(2)
I agree with you, although the locking in singletons can be customized. But there's another point: the injection is only performed on bean creation and then used by multiple callers (concurrently or not).Symmetrical
The persistence context is transaction-scoped by default.Papandreou

© 2022 - 2024 — McMap. All rights reserved.