Java JPA EntityManager没有';GCing时无法关闭(性能问题)
我们一直在使用基于注释的JPA和Hibernate作为JPA适配器。 我们必须使用spring调度器安排一个作业来刷新整个表数据。 代码如下:Java JPA EntityManager没有';GCing时无法关闭(性能问题),java,performance,hibernate,jpa,entitymanager,Java,Performance,Hibernate,Jpa,Entitymanager,我们一直在使用基于注释的JPA和Hibernate作为JPA适配器。 我们必须使用spring调度器安排一个作业来刷新整个表数据。 代码如下: @Scheduled(fixedDelay=120000) public void refreshTable() { EntityManager em = null; try { EntityManagerFactory emf = entityManager.getEntityManagerFactory();
@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.");
}
}
}
这用于构建内存利用率并导致应用程序挂起
我们补充说,在最后一个街区的尽头
if(em != null){
em.close();
}
解决了记忆问题
那么,为什么EntityManager在被GC’ed时不执行close()?JPA连接器有各种与之相关的连接,并且它不会关闭所有连接,而等待垃圾收集器执行这项操作并不是明智的做法 在不再需要连接时关闭连接(即EntityManager和EntityManager Factory)是解决此问题的最佳方法 希望这有帮助! 祝你好运