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?

  • 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 '17 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 '17 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 '17 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 '17 at 11:30
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.

| improve this answer | |
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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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