I’m working on an application that needs to do some database operations.
I created a static variable for EntityManagerFactory and initializeded it in the method that gets called by the application
if (emf == null) {
emf = Persistence.createEntityManagerFactory("example");
}
try {
em = emf.createEntityManager();
} catch (Exception ex) {
logger.error(ex.getMessage());
}
Is this thread-safe? If I create the EntityManagerFactory in a synchronized block, the number of the waiting threads increases and crashes the application.
I looked at the docs to see whether the Persistence.createEntityManagerFactory is thread-safe without any success.
Please direct me to the right resources.
An easy way to “solve” this would be to use a helper class (a la
HibernateUtil) and to initialize theEntityManagerFactoryin a static initialization block. Something like this:And the “problem” is gone.