Java Design Patterns – Is Storing the Connection Pool in a Singleton a Bad Practice?

design-patternsjava

I just read this question and the answer claims:

"Lets assume db connection object is singleton in my application"

This is a must not. Your database connection MUST NEVER BE (yes, bolded and
with capitals to make sure you and every reader never make this
mistake) a singleton object. Your Connection con MUST NOT be part of a
singleton to keep it open all the time. Instead, use a proper database
connection pool that will take care of opening the necessary physical
database connections and keep them alive through the live of your
application.

We of course use a connection pool to take care of our, well, connections. Still, we store this pool in a singleton. How else would one ensure that it lives throughout the application? Ist his bad practice?

Best Answer

I think the quoted answer is mainly stating an opinion.

The one fact in that answer is about the "per classloader" aspect.

In other words: unless you are in a situation, where that "multiple classloaders" part comes in there are no technical reasons to not use a singleton.

Of course, the key element would be to implement a "correct" singleton; for example by using a Java enum for that.

Related Topic