import java.sql.Connection;
import java.sql.DriverManager;

public class JdbcHook {
	/**
	 * A database connection reference that is opened in the class constructor
	 * and is closed in the finalize method.
	 */
	private Connection conn = null;

	/**
	 * Database connection data.
	 */
	public static String DBurl = "jdbc:postgresql://localhost:5432/test?user=postgres";
	public static String DBdriver = "org.postgresql.Driver";
	static {
		/**
		 * Check to see if parameters are set to override defaults:
		 */
		try {
			DBurl = System.getProperty("DBurl", DBurl);
			DBdriver = System.getProperty("DBdriver", DBdriver);
		} catch (Exception ee) {
			ee.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		new JdbcHook();
	}

	public JdbcHook() throws Exception {
		Class.forName(DBdriver);
		conn = DriverManager.getConnection(DBurl);
		// set up service termination hook (gets called
		// when the JVM terminates from a signal):
		MyJdbcConnectionShutdownHook sh = new MyJdbcConnectionShutdownHook(this);
		Runtime.getRuntime().addShutdownHook(sh);
	}

	/**
	 * Free resources
	 */
	public void freeResources() {
		System.out.println("\nJdbcHook.freeResources()\n");
		try {
			if (conn != null && conn.isClosed() == false) {
				conn.close();
			}
		} catch (Exception ee) {
			System.out.println("Error freeing resources: " + ee);
			ee.printStackTrace();
		}
	}

	/**
	 * The finalize method will be called to close the database connection
	 * 
	 * @throws Throwable
	 */
	protected void finalize() throws Throwable {
		try {
			freeResources();
		} finally {
			super.finalize();
		}
	}

}

/**
 * Shutdown hook class
 */
class MyJdbcConnectionShutdownHook extends Thread {
	public MyJdbcConnectionShutdownHook(JdbcHook managedClass) {
		super();
		this.managedClass = managedClass;
	}

	private JdbcHook managedClass;

	public void run() {
		System.out
				.println("JdbcHook MyJdbcConnectionShutdownHook thread started");
		try {
			managedClass.freeResources();
		} catch (Exception ee) {
			ee.printStackTrace();
		}
	}
}
