how to use JDBC Connection Pools in a standalone application?
Joined: Oct 17, 2006
I have a question about how to use JDBC Connection Pools in an application. I know well about connection pool itself, but I am not quite sure how to keep the pool management object alive all the time to avoid being destroyed by garbage collection.
for example, at the website: http://www.developer.com/java/other/article.php/626291, there is a simple connection pool implementation. there are three classes:JDBCConnection, the application's gateway to the database; JDBCConnectionImpl, the real class/object to provide connection; and JDBCPool, the management class to manage connection pool composed by JDBCConnectionImpl. JDBCPool is designed by Singleton pattern to make sure only one instance. supposing there is only one client to use connection for many times, I guess it's ok because this client first needs instantiate JDBCPool and JDBCConnectionImpl and then will hold the reference to JDBCPool all the time. but how about many clients want to use this JDBCPool? supposing client1 finishes using JDBCPool and quits, then JDBCPool will be destroyed by garbage collection since there is no reference to it, also all the connections of JDBCConnectionImpl in this pool will be destroyed too. that means the next client needs recreate pool and connections! so my question is that if there is a way to keep pool management instance alive all the time to provide connection to any client at any time. I guess maybe I can set the pool management class as daemon thread to solve this problem, but I am not quite sure. besides, there is some other problems about daemon thread, for example, how to make sure there is only one daemon instance? how to quit it gracefully? because once the whole application quits, the daemon thread also quits by force. in that case, all the connections in the pool won't get chance to close.
I know there is another solution by JNDI if we develop servlet application. Tomcat provides an easy way to setup JNDI database pooling source that is available to JSP and Servlet. but how about a standalone application? I mean there is no JNDI service provider. it seems a good solution to combine Commons DBCP with JNID or Apache's Naming (http://jakarta.apache.org/commons/dbcp/index.html). but still, I don't know how to keep pool management instance alive all the time. once we create a JNDI enviroment or naming, if it will save in the memory automatically all the time? or we must implement it as a daemon thread?