Listen to this post
Create a manager class to represent a pool of reusable resources. Clients will access the manager to obtain an instance of the resource and return it when their task is complete.
Connections are to be made to a data resource on a server. The server will allow from 1 to 255 connections to be made. If one connection is made, then clients must wait for the connection to be available, but the server’s performance will be fast. If 255 connections are made, then clients need not wait for an available connection, but the server will bog down servicing so many connections. It is unpredictable what the best balance point is for optimal throughput.
An Object Pool could be used to manage a set of reusable connection objects. The number of objects is encapsulated and, therefore, easy to change.
Qualities and principles
The Object Pool separates the concerns of use from creation, but also the nature of the pool itself. How many objects are in it, if they are reused or remade each time, if they are used by more than one client (load balanced), all these things are encapsulated and therefore easily changeable. The managed objects are substitutable for each other.
Testing the manager itself is fairly straightforward:
- Tests can be written to ensure the proper object type is created, that the manager blocks when it should, etc.
- If the pool collection is given protected access, a unit test can subclass the manager and thus observe the size of the pool under different scenarios.
- Testing the managed objects depends on their nature and design. Often, they are designed using other patterns.
Questions and concerns
One decision that must always be addressed with the Object Pool is whether or not to make the pool size dynamic. The setPoolSize(int) method is optional and should only be added if changing the pool size will not violate any system contracts, and if different application contexts will require it. The default option is to keep the pool size static.