且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

EntityManager 真的是线程安全的吗?

更新时间:2023-02-13 23:34:21

不,EntityManager 不是线程安全的.Adam Bien 也是正确的.你只是没有正确看待这个问题.他回答的问题不是 EntityManager 是否是线程安全的,他说在无状态会话 bean 中使用容器管理的 EntityManger 是安全的,它是安全的.然后他解释了允许容器发挥其魔力的规范的推理和措辞——每个实例只看到一个方法调用的序列化序列".这允许容器注入为每个方法调用具有不同的 EntityManager 上下文,类似于每个调用如何绑定到它们自己的事务和隔离的资源.

No, an EntityManager is NOT thread safe. Adam Bien though is also correct. You are just not looking at the question correctly. The question he is answering isn't if an EntityManager is thread safe, he is stating that using container managed EntityManger in a stateless session bean is safe, which it is. He then explains the reasoning and wording of the spec that allows the container to work its magic - "each instance sees only a serialized sequence of method calls". That allows container injection to have different EntityManager contexts per method invocation, similar to how each invocation can be tied to their own transaction and isolated resources.

注入实际上只是注入一个 EntityManager 代理,该代理使容器可以控制下面的 JPA EntityManager 的生命周期,从而将其绑定到线程和事务.

Injection is really just injecting an EntityManager proxy that gives the container control over the lifecycle of the JPA EntityManagers underneath, allowing it to be tied to the thread and the transaction.

所以 EntityManager 不是线程安全的,但容器注入的 EntityManager 代理需要在无状态会话 bean 中安全使用.

So an EntityManager is NOT thread safe, but the container injected EntityManager proxies are required to be safe to use within stateless session beans.