开发者

How is threadsafty guranteed with @PersistenceContext?

开发者 https://www.devze.com 2022-12-15 11:47 出处:网络
According to many examples it is possible to inject an EntityManager into @Stateless or @Singleton EJBs like this:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号