views:

90

answers:

1

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.

+1  A: 

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

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:

  1. Reusable objects shouldn't have a state (or their state should be 'cleared' in releaseReusable method)

  2. 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).

Roman