title: When should EntityManagerFactory instance be created/opened?
body: <p>Ok, I read bunch of articles/examples how to write Entity Manager Factory in singleton.</p>
  
  <p>One of them easiest for me to understand a bit:</p>
  
  <p><a href="http://javanotepad.blogspot.com/2007/05/jpa-entitymanagerfactory-in-web.html">http://javanotepad.blogspot.com/2007/05/jpa-entitymanagerfactory-in-web.html</a></p>
  
  <p>I learned that <strong>EntityManagerFactory (EMF) should only be created once preferably in application scope.</strong> </p>
  
  <p>And also make sure to close the EMF once it's used (?)</p>
  
  <p>So I wrote EMF helper class for business methods to use:</p>
  
  <pre><code>public class EmProvider {
  
      private static final String DB_PU = "KogaAlphaPU";
  
      public static final boolean DEBUG = true;
  
      private static final EmProvider singleton = new EmProvider();
  
      private EntityManagerFactory emf;
  
      private EmProvider() {}
  
      public static EmProvider getInstance() {
          return singleton;
      }
  
  
      public EntityManagerFactory getEntityManagerFactory() {
          if(emf == null) {
              emf = Persistence.createEntityManagerFactory(DB_PU);
          }
          if(DEBUG) {
              System.out.println("factory created on: " + new Date());
          }
          return emf;
      }
  
      public void closeEmf() {
          if(emf.isOpen() || emf != null) {
              emf.close();
          }
          emf = null;
          if(DEBUG) {
              System.out.println("EMF closed at: " + new Date());
          }
      }
  
  }//end class
  </code></pre>
  
  <p><strong>And my method using EmProvider:</strong></p>
  
  <pre><code>public String foo() {
      EntityManager em = null;
      List&lt;Object[]&gt; out = null;
      try {
  
          em = EmProvider.getInstance().getEntityManagerFactory().createEntityManager();
          Query query = em.createNativeQuery(JPQL_JOIN); //just some random query 
          out = query.getResultList();
      }
      catch(Exception e) {
          //handle error....
      }
      finally {
          if(em != null) {
               em.close(); //make sure to close EntityManager
          }
          //should I not close the EMF itself here?????
          EmProvider.getInstance().closeEmf();
      }
  </code></pre>
  
  <p>I made sure to close EntityManager (em) within method level as suggested. But <strong>when should EntityManagerFactory be closed then?</strong> And why EMF has to be singleton so bad??? I read about concurrency issues but as I am not experienced multi-thread-grammer, I can't really be clear on this idea.</p>