Spring:@PersistenceContext和@Autowired线程安全吗? [英] Spring : @PersistenceContext and @Autowired thread safety?

查看:449
本文介绍了Spring:@PersistenceContext和@Autowired线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于此示例:

@Service
public class Purchase {
  @PersistenceContext
  private EntityManager em;

  @Autowired
  private PurchaseDAO dao;

  private String normalField;

  .... // methods, operations, etc
}

如果我误会了,请帮助纠正我:

Please help correct me if im mistaken :

  1. 服务类 Purchase PurchaseDAO 是由spring管理的单例
  2. 服务类的字段 normalField 不是线程安全的,因为单例是由许多人共享的单个对象
  3. 假设 @ Repository-annotated-PurchaseDAO 没有任何字段,这意味着它是线程安全的,将在spring之前自动注入
  4. EntityManager 实例也是一个线程安全的属性,因为 @PersistenceContext 将确保使用当前事务的entityManager.
  1. The service class Purchase and the PurchaseDAO are singletons that are managed by spring
  2. The service class's field normalField is not threadsafe, because singleton is a single object shared by many
  3. Let's assume the @Repository-annotated-PurchaseDAO doesnt have any field, which means it's threadsafe, will be injected automatically by spring
  4. The EntityManager instance is also a threadsafe property because @PersistenceContext will make sure that the entityManager of the current transaction will be used.

谢谢!

推荐答案

  1. 默认情况下,它们是单例(由Spring托管时),除非您另外配置了它们(通过xml配置或带有批注的注释,可以使用@Scope进行设置).
  2. 是,不是.是的,从多个线程可以同时访问和修改它的角度来看,这是不安全的,并且因为它取决于数据类型并且String是不可变的(并且至少被认为是线程安全的),因此不安全.如果两个不同的线程试图在同一时刻将新字符串存储在成员变量中,则可能会崩溃.
  3. 是的,再也没有.如果DAO没有内部状态,是的,我想说它是线程安全的,但是它正在处理的对象可能不是(尽管如果使用的是JPA实体,则应该是).
  4. 至少Hibernate的文档说EntityManagers不是线程安全的,但是当使用Spring注入的EntityManager时,这应该不是问题.

SpringSource论坛: 我一直在论坛上寻找相同问题的答案...普遍的共识似乎是,尽管EntityManager并不是根据JPA规范是线程安全的,但Spring通过其EntityManager代理注入的EntityManager可能是.

休眠: EntityManager是一种廉价的,非线程安全的对象,应针对单个业务流程,单个工作单元使用一次,然后丢弃.除非需要,否则EntityManager不会获得JDBC连接(或数据源),因此即使不确定要满足特定请求是否需要数据访问,也可以安全地打开和关闭EntityManager.

这篇关于Spring:@PersistenceContext和@Autowired线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆