【问题标题】:JPA EntityManager doesn't get closed while GCing (Performance issue)GCing 时 JPA EntityManager 没有关闭(性能问题)
【发布时间】:2014-03-17 05:16:22
【问题描述】:

我们一直使用基于注解的 JPA 和 Hibernate 作为 JpaVendorAdapter。 我们必须使用 spring scheduler 安排一个作业来刷新整个表数据。 代码如下,

@Scheduled(fixedDelay=120000)
public void refreshTable() {

    EntityManager em = null;
    try {

        EntityManagerFactory emf = entityManager.getEntityManagerFactory();
        em = emf.createEntityManager();

        em.getTransaction().begin();

        /// do something like delete and fill table
        // this block is done for the sake of batch mode operation

        em.getTransaction().commit();

    } catch (Exception e) {
        logger.error("Failed to refresh table", e);
    } finally{
        if(em != null && em.getTransaction().isActive()){
            em.getTransaction().rollback();
            logger.info("Failure while refreshing table, rolling back transaction.");
        }
    }
}

这用于构建内存利用率并导致应用程序挂起。

我们在 finally 块的末尾添加了,

if(em != null){
   em.close();
}

这解决了内存问题。

那么,为什么 EntityManager 在被 GC 时不执行 close()?

【问题讨论】:

    标签: java performance hibernate jpa entitymanager


    【解决方案1】:

    JPAConnector 具有与之关联的各种连接,它不会关闭所有连接,而等待垃圾收集器执行此操作不是明智的方法。

    在不再需要时关闭连接(即 EntityManager 和 EntityManagerFactory)是解决此问题的最佳方法。

    希望这会有所帮助! 祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-09
      • 1970-01-01
      • 2012-04-18
      • 2013-07-25
      • 2013-11-19
      • 1970-01-01
      • 2011-01-22
      • 1970-01-01
      相关资源
      最近更新 更多