user1846299
user1846299

Reputation: 1

Why database connection object or connection pool needs to be made singleton?

I have gone through couple of articles on singleton example. And I could see that developers sometimes make the database connection object or connection manager as singleton implementation. In some of the posts even it was advised to use Database connection pool. Well Singleton means to create a single instance, so basically we restrict the access. e.g. Printer or hardware access, logger access in which we try to restrict the access of the user to one at a time using singleton. However what is the purpose of using singleton in DB connection objects? If I can understand correctly creating a Database connection as singleton means that app server will have only one instance. Does this mean only one user can access the Database connection and next user has to wait until the connection is closed? Please advise.

Upvotes: 0

Views: 2151

Answers (2)

Pawel Solarski
Pawel Solarski

Reputation: 1048

Q: "However what is the purpose of using singleton in DB connection objects?"
A: There is (almost always) none. So your thinking is correct.

Q: "Does this mean only one user can access the Database connection and next user has to wait until the connection is closed?"
A: Depends (to first part) and No (to second part after "and").

In single-threaded application only one user will use the database at one time and another will wait, until dispatch of first user ends but not when the connection is closed. Once connection is closed, you need to create another connection to make use of database.

In multi-threaded application many threads may be using the same connection instance and result really depends on the vendor implementation: may block dispatching (effectively transforming your app to single-threaded app) or throw exceptions or even something different. However, such design in multi-threaded app is in my opinion a programmer-error.

Upvotes: 0

madth3
madth3

Reputation: 7344

I think you understand correctly the implication of making the connection itself a singleton. Generally it is not a good idea (although in some very particular case it could make sense).

Making a connection manager or a connection pool a singleton is completely different. The pool itself would handle a collection of connections and it can create new as they are needed (up to a limit) or re-use the ones that have been already used and discarded.

Having several connection pools at the same time would lose the advantages of the pool:

  • It would be harder to control the total number of connections open
  • One pool could be creating connections while other could have connections available

Hope this helps to clarify the subject. You might want to read more on connection pools.

Upvotes: 2

Related Questions