Object Pool pattern (and Connection Pool is a particular case of it) is greatly described in Mark Grand's 'Patterns in Java. Vol. 1'.
Here is a basic class diagram (from google images):
Main idea: Client
shouldn't create Reusable
objects by himself. Instead of that he should use ReusablePool
. To get Reusable
object he should call acquireReusable
. When he doesn't need Reusable
object any more he should put it back trough calling releaseReusable
.
ReusablePool
contains a list of Reusable
objects. When Client
asks for Reusable
, pool looks for existing free Reusable
. If all Reusable
objects are acquired then if list size is less then maxSize
ReusablePool
creates one more Reusable
object. When list size is equals to maxSize
pool doesn't create new Reusable
. Instead of that it waits until some other client give him back any Reusable
object.
From this description you can make 2 conclusions:
Reusable
objects shouldn't have a state (or their state should be 'cleared' in releaseReusable
method)
ReusablePool
is usually a part of multithreading applications and all synchronization stuff inside all its methods should be implemented in a proper way (and it's not an easy task).