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:
Clientshouldn’t createReusableobjects by himself. Instead of that he should useReusablePool. To getReusableobject he should callacquireReusable. When he doesn’t needReusableobject any more he should put it back trough callingreleaseReusable.ReusablePoolcontains a list ofReusableobjects. WhenClientasks forReusable, pool looks for existing freeReusable. If allReusableobjects are acquired then if list size is less thenmaxSizeReusablePoolcreates one moreReusableobject. When list size is equals tomaxSizepool doesn’t create newReusable. Instead of that it waits until some other client give him back anyReusableobject.From this description you can make 2 conclusions:
Reusableobjects shouldn’t have a state (or their state should be ‘cleared’ inreleaseReusablemethod)ReusablePoolis 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).