Design for ConnectionPool
When some one asks you to write (do / 开发者_开发百科depict) design for Connection Pool in a Java interview what would you typically write.
Do you write code for connection pool or do you depict the Class diagrams. Can somebody please explain the design of Connection pool.
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):
alt text http://img13.imageshack.us/img13/8448/poolz.png
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' inreleaseReusable
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).
精彩评论