4

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?

4
  • 1
    A connection pool might be one of the only valid use cases for a singleton pattern (which you usually want to avoid). I would be fine with it.
    – f1sh
    Feb 1, 2017 at 10:29
  • 7
    I think the answer means what you have done. Connections themselves should not be singletons, but CAN be managed by a singleton.
    – jr593
    Feb 1, 2017 at 10:30
  • 1
    Like jr593, I think you just misread the answer. Your implementation of Connection must not be designed as singleton, but your Connection Pool may be a singleton.
    – SME_Dev
    Feb 1, 2017 at 10:48
  • I too misread the text, I think is not a bad practice connections are a limited resource and are both expensive to initially create and then maintain over time. If not a singleton your system must still have access to a single instance of this pool but not a single instance to the connection.
    – Omar Ayala
    Feb 1, 2017 at 11:30

2 Answers 2

1

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.

1

What the author of the quote says is that the connection must never be a singleton, not stored in a singleton. I can't imagine a connection as a singleton with status like "connected", "available", etc... Pools are made for this.

On an application I do the same thing as you, the connections are stored in a pool held by a singleton, so that any thread can use them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.