【问题标题】:Using the same EntityManager across multiple threads跨多个线程使用相同的 EntityManager
【发布时间】:2015-11-18 00:28:00
【问题描述】:

我有一个 JPA 环境,它有一个应用程序管理的 EntityManager。我手动创建 entityManagerFactory 并从中创建 EntityManager。我想在多个线程中使用相同的 EntityManager。文档说 EntityManager 不是线程安全的,但我的所有操作都只会是读取,不会通过 EntityManager 发生写入。我也对缓存中的数据进行了超时以确保一致性。在这种情况下,是否可以跨线程使用相同的 EntityManager 实例?或者跨线程使用相同的EntityManager是否有任何副作用/错误数据。

谢谢

【问题讨论】:

  • 即使你的 EntityManager 是只读的,它仍然有一个内部状态。使用 EntityManagerFactory 在线程之间共享,并为每个线程使用不同的 EntityManager

标签: java multithreading jpa entitymanager


【解决方案1】:

可以肯定的是,只需使用 synchronizedEntityManager 实例锁定在您使用它的任何位置。

所以不要写

em.persist(...);

synchronized (em) {
    em.persist(...);
}

你可以read up about the locking mechanism here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多