A DB connection should not normally be a Singleton.
Two reasons:
- many DB drivers are not thread safe. Using a singleton means that if you have many threads, they will all share the same connection. The singleton pattern does not give you thread saftey. It merely allows many threads to easily share a “global” instance.
- Personally, I think Singleton often leads to bad design: See this post (by somebody else) http://tech.puredanger.com/2007/07/03/pattern-hate-singleton/
Instead of doing this consider a database pool. The pool is shared (and could be a singleton if you wanted). When you need to do database work your code does this:
getConnectioFromPool();
doWork()
closeConnection() // releases back to pool
Sample Pool Libraries:
- http://commons.apache.org/dbcp/
- http://jolbox.com/