java JPA EntityManager在GCing时未关闭(性能问题)
我们一直在使用基于注释的JPA和Hibernate作为JPA适配器。 我们必须使用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.");
}
}
}
这用于提高内存利用率,并导致应用程序挂起
我们补充说,在最后一个街区的尽头
if(em != null){
em.close();
}
解决了记忆问题
那么,为什么EntityManager在执行GC时不执行close()
# 1 楼答案
JPAConnector有各种与之相关的连接,它不会关闭所有连接,而等待垃圾收集器完成这些连接并不是明智的做法
在不再需要时关闭连接(即EntityManager和EntityManager Factory),是解决此问题的最佳方法
希望这有帮助! 祝你好运