Skip to content
Advertisement

Should EntityManagerFactory be closed at application shutdown?

I have a Java application that has a GUI made with Swing and that uses two databases interchangeably. One of the two databases is mongoDB and the other one is MySQL. Which database to use is chosen with a command line option. For the MySQL database I am also using Hibernate and JPA. The code I have looks like this:

JavaScript

In mysql case I am creating an EntityManagerFactory and an EntityManager. The entityManager created here is passed as argument to the constructor of the repositories and used throughout the whole life of the application. I was wondering what is the best practice about closing the entityManager and the factory. Searching in the documentation I found this:

Closing an EntityManagerFactory should not be taken lightly. It is much better to keep a factory open for a long period of time than to repeatedly create and close new factories. Thus, most applications will never close the factory, or only close it when the application is exiting.

So I was wondering, what is the difference between closing the factory and entity manager at application shutdown and not closing it? Also in my case I’m declaring emf and entityManager inside the mysql case since are not required for mongodb. In order to close them at application shutdown what should I do? I found something about Runtime.getRuntime().addShutdownHook(). I tried using it like the code below, but it seems like it is not working.

JavaScript

Advertisement

Answer

Short answer, yes, it should be closed. And the reason can be found at this answer:

The JVM will release all active resources upon termination; however, this does not ensure that the other end will free the resource too, so explicitly closing resources is in every programmer’s best interest.

So in my case, it is true that the EntityManager and factory are closed at application shutdown, but this does not ensure that they are properly dealt with on the other end. I didn’t mention it in my question, but in fact the same thing holds true for the Mongo Client as well (see this answer):

If you ever re-deploy your web application without first restarting your application server, you must ensure that the MongoClient is closed when your web application is shutdown.

About the implementation I made an interface that I called DBInitializer. I instantiated an object of type MongoInitializer or MySQLInitializer (both implementing DBInitializer) inside the main method. See code for more clarity.

DBInitializer:

JavaScript

MySQLInitializer:

JavaScript

MongoInitializer:

JavaScript

App:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement