Pooling (Singleton) Objects Against Connection Pools

dependency-injectionspring

Given the following scenario

  • A canned enterprise application that maintains its own connection pool
  • A homegrown client application to the enterprise app. This app is built using Spring framework, with the DAO pattern

While I may have a simplistic view of this, I think the following line of thinking is sound:

  • Having a fixed pool of DAO objects, holding on to connection objects from the pool. Clearly, the pool should be capable of scaling up (or down depending on need) and the connection objects must outnumber the DAOs by a healthy margin. Good

  • Instantiating brand new DAOs for every request to access the enterprise app; each DAO will attempt to grab a connection from the pool and release it when it's done. Bad

Since these are service objects, there will be no (mutable) state held by the objects (reduced risk of concurrency issues)

I also think that with #1, there should be little to no resource contention, while in #2, there'll almost always be a DAO waiting to be serviced. Is my thinking correct and what could go wrong?

Best Answer

Entity Framework and Linq to SQL both instantiate DAO's as needed.

DAO's in Entity Framework (they're called Data Contexts) are deliberately designed to be lightweight to instantiate, so you create a new one each time a data access is required. Sometimes folks try to cache these Data Contexts, but that is a design error, and it can cause concurrency problems (DataContext is not thread-safe). In general, you create one DataContext object for each Unit of Work.

Entity Framework is most commonly used with SQL Server; SQL Server maintains a pool of "recently-used connections" that can be reused, so that the process of opening a new connection is also as fast as possible.

Further Reading
Linq to SQL DataContext Lifetime Management
Building N-Tier Applications with Entity Framework ... for various approaches.