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?
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.
精彩评论