package beaform.dao;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * A handler for the graph database using JTA.
 *
 * @author Steven Post
 *
 */
public final class GraphDbHandler {

	/** The instance of this singleton */
	private static GraphDbHandler instance;

	/** A lock for accessing the instance */
	private static final Object INSTANCELOCK = new Object();

	/** The global {@link EntityManager} */
	private final EntityManager entityManager;

	/** The global EntityManager factory */
	private final EntityManagerFactory entityManagerFact;

	private GraphDbHandler(final String persistenceUnit) {
		this.entityManagerFact = Persistence.createEntityManagerFactory(persistenceUnit);

		this.entityManager = this.entityManagerFact.createEntityManager();

		final ShutDownHook shutdownHook = new ShutDownHook(this.entityManager, this.entityManagerFact);
		Runtime.getRuntime().addShutdownHook(shutdownHook);
	}

	/**
	 * Get the instance of this handler.
	 * @param persistenceUnit the persistence unit to use
	 */
	public static void initInstance(final String persistenceUnit) {
		synchronized (INSTANCELOCK) {
			if (instance == null) {
				instance = new GraphDbHandler(persistenceUnit);
			}
		}
	}

	/**
	 * Get the instance of this handler.
	 * @return the instance
	 */
	public static GraphDbHandler getInstance() {
		synchronized (INSTANCELOCK) {
			if (instance == null) {
				throw new IllegalStateException("The instance is not yet initialised");
			}
			return instance;
		}
	}

	/**
	 * Get the instance of this handler.
	 */
	public static void clearInstance() {
		synchronized (INSTANCELOCK) {
			if (instance == null) {
				throw new IllegalStateException("The instance is not yet initialised");
			}
			instance.entityManager.close();
			instance.entityManagerFact.close();
			instance = null;
		}
	}

	/**
	 * Getter for the entity manager.
	 *
	 * @return the entity manager
	 */
	public EntityManager getEntityManager() {
		return this.entityManager;
	}

}

@@ -627,16 +627,85 @@
 rFact;%0A%0A
+%09/** The shutdown hook */%0A%09private final ShutDownHook shutdownHook;%0A%0A
 %09private
@@ -909,35 +909,21 @@
 r();%0A%0A%09%09
-final ShutDownHook 
+this.
 shutdown
@@ -1030,16 +1030,21 @@
 ownHook(
+this.
 shutdown
@@ -1925,32 +1925,99 @@
 erFact.close();%0A
+%09%09%09Runtime.getRuntime().removeShutdownHook(instance.shutdownHook);%0A
 %09%09%09instance = nu

Remove a shutdown hook when the GraphDbHandler is cleared