title: EntityManager.close() Not Closing The Connections to Database Tomcat
body: <p>Here is my JPA Utill Class....</p>
  
  <pre><code>private static Logger logger=Logger.getLogger(JPAUtil.class);
  private static EntityManager entityManager = null;
  private static final ThreadLocal&lt;EntityManager&gt; threadLocal;
  
  private static EntityManagerFactory emf = null;
  
  static 
  {
      try {
  
              emf = Persistence.createEntityManagerFactory("XYZ");
              threadLocal = new ThreadLocal&lt;EntityManager&gt;();
  
      } catch (Throwable ex) {
          logger.info("JPAUtil Exception",ex);
          throw new ExceptionInInitializerError(ex);
      }
  }
  
  public static EntityManager getEntityManager() {
      try {
               entityManager = threadLocal.get();
  
          if (entityManager == null ||  !entityManager.isOpen()) {
  
              JPAUtil.entityManager = emf.createEntityManager();
              threadLocal.set(entityManager);
  
          }else if(!emf.isOpen())
          {
               entityManager = threadLocal.get();
              emf = Persistence.createEntityManagerFactory("XYZ");
              JPAUtil.entityManager = emf.createEntityManager();
              threadLocal.set(entityManager);
          }
      } catch (Throwable ex) {
          logger.info("JPAUtil Exception",ex);
          throw new ExceptionInInitializerError(ex);
      }
      return JPAUtil.entityManager;
  }
  
  public static void closeEntityManager() {
      EntityManager entityManager = threadLocal.get();
      if (entityManager != null) {
          entityManager.close();
          threadLocal.set(null);
      }
  
      }
  public static void closeEntityManagerFactory() {
      emf.close();
      }
  
  public static void commit() {
      if (!entityManager.getTransaction().isActive()){
          entityManager.getTransaction().begin();
      }
  entityManager.getTransaction().commit();
  }
  public static void rollback() {
      if (!entityManager.getTransaction().isActive()){
          entityManager.getTransaction().begin();
      }
      entityManager.getTransaction().rollback();
  }
  </code></pre>
  
  <p></p>
  
  <p><p>
  And After each and every transactions i am closing entitymanager....with </p>
  
  <p>finally block...and later i came to Know that even in select query we need to </p>
  
  <p>begin transaction and commit it...so i did try that in my application Home </p>
  
  <p>page Just executing 2 select query and in the server mysql is Occupying the memory the most....with the eclipse MAT i Anallise the Memory Leak....</p>
  
  <p><img src="https://i.stack.imgur.com/FbVZ0.png" alt="MAT Result"> </p>
  
  <p>As per my understanding since i am using tomcat i cant do connection pooling..and we will be moving to jboss...but till the i would like to patch this....any help would be appreciated :) :)</p>