RLK.JPA
EntityManager is not closed on exit
RLK (Resource Leak) issues are reported when resources are allocated but not properly disposed after use. Failing to properly dispose a resource can lead to such problems as:
- too many files being open
- an application not being able to access a temporary file when it is needed
An RLK.JPA warning indicates that a JPA object is not closed on exit.
Vulnerability and risk
Resources such as entityManager must be explicitly closed before returning, or you will no longer have access to that resource again, unless you're keeping it in some registry.
If you don't close resources, your entities will be kept as attached, even after you've finished using them. Your context will be kept alive even when you can no longer access your EM.
Mitigation and prevention
Explicitly close all resources that have the close method, even those that you think are not doing anything significant. Future code changes will then be safe from such errors.
Vulnerable code example 1
public class ResourceLeakJpaEntityManager {
public void test() {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("Books");
}
}
Klocwork reports an RLK.JPA defect on line 4, indicating: 'entityManagerFactory' object is not closed on exit.
Fixed code example 1
public class ResourceLeakJpaEntityManager {
public void test() {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("Books");
entityManagerFactory.close();
}
}
In this example, Klocwork no longer reports a defect as the entities are closed on line 5.
Vulnerable code example 2
public class ResourceLeakJpaEntityManager {
public void test() {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("Books");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManagerFactory.close();
}
}
Klocwork reports an RLK.JPA defect on line 5, indicating: 'entityManager' object is not closed on exit.
Fixed code example 2
public class ResourceLeakJpaEntityManager {
public void test() {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("Books");
EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.close();
entityManagerFactory.close();
}
}
In this example, Klocwork no longer reports a defect as the entities are closed.