Skip to content

Object Pool Design Pattern – Sequence Diagram

Last updated on 2014-09-07

An Object pool is used when object allocation is expensive, either in time or memory, and you know there is a limited number of instances that need to be alive at all times (this is not a requirement, but if you are always adding objects to the pool without releasing them, you are not making use of the pool at all). A typical class diagram for an object pool would look something like this:

object.pool.class.diagram

yUML code:
[Client]->[ObjectPool|getInstance():ObjectPool;borrowObject():Object;returnObject(Object)]
[ObjectPool]<>-pool 0..*>[Object]

(disclaimer: I saw many different ways to name the methods of the ObjectPool and decided to stick with those used by the Apache Pool project. Hope you like them)

This diagram shows us that the client can only get Object instances through the ObjectPool but we are still left wondering what happens inside the pool. To show this, we need to use… you guessed it, a Sequence Diagram! First, let’s see what happens when an object is borrowed from the pool:

object.pool.borrow.sequence.diagram

WebSequenceDiagrams code:
Client->ObjectPool:borrowObject()
alt pool.size() > 0
ObjectPool->ObjectPool:object = pool.remove()
ObjectPool-->Client:object
else else
ObjectPool->Object:object = new()
ObjectPool-->Client:object
end

And how it is returned to the pool:

object.pool.return.sequence.diagram

WebSequenceDiagrams code:
Client->ObjectPool:returnObject(object)
ObjectPool->ObjectPool:pool.add(object)
ObjectPool-->Client:

Simple, right? When an object is borrowed, the pool tries to take one from an internal pool of objects. If this pool is empty, it creates one and returns it. When the is finished with the object, it simply returns it to the pool. This is the basic concept.

Now there are a number of things I have left out: First, the pool may be limited in size; in this case, the pool can either return null or block the client’s request. Second, the objects borrowed from the pool must be in a usable state. This can be achieved by either setting up this state before giving the object to the client, or by cleaning the objects when they are returned to the pool (for example, if you are developing a connection pool, you should check that the connections are open before they are given to the client, or something like that).

Enjoy your pool!

Enhanced by Zemanta
Published inProgramming

Be First to Comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.