Introduction to the Object Pool Design Pattern

No.of Views768
Bookmarked0 times
Downloads 
Votes0
By  Chinna Srihari   On  21 Oct 2010 11:10:21
Tag : Design Patterns , General
As a developer we might have noticed that creation of some class is very difficult and number of time that we need to create. Such object creation every time is very expensive in terms of system resources. If we can cache that kind of object show how will surely boost the application performance and resource usage can be saved. This where object pool design pattern will help development community to cache the objects. Some time it is also called as Object cache or Resource cache design pattern.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

What is object pool?
 
As a developer we might have noticed that creation of some class is very difficult and number of time that we need to create. Such object creation every time is very expensive in terms of system resources. If we can cache that kind of object show how will surely boost the application performance and resource usage can be saved. This where object pool design pattern will help development community to cache the objects. Some time it is also called as Object cache or Resource cache design pattern.
 
It is adviced to keep all Reusable expensive objects that are not currently in use in the container so that they can be managed by one rational policy. To achieve this, the Reusable Pool class is designed to be a singleton class.
 
Support of C# for pooling objects
 
Queue Class
Queue is a Simple DataStucture which allows Add or Remove of Items at one of the ends only. It is basically called as First in First out data structure. The item which is added first is the first one to be removed. Default initial size of the queue is 32. Make sure that whenever Queue is initialized define the size of the queue, that Add and Remove operations are performed perfectly.
 
Enqueue () method will add the item in the last available portion and Dequeue () method will remove and return the oldest item in the queue. Set us see the code how it helps to implement the object pool design pattern.
EX: Simple Example
public class QueuedPool: Queue
       {
        public Person Fetch()
        {
            return (Person)Dequeue();
        }
 
        public void Store(Person person)
        {
            Enqueue(person);
        }
 
        public void ClearAll()
        {
            base.Clear();
        }
}
At client side
QueuedPool queuePool = new QueuedPool();
 queuePool.Store(new Person());
Person p = queuePool.Fetch();
EX: Using Generics
public interface IStore<T>
   {
        T Fetch();
        void Store(T obj);
        int Count { get;}
        void ClearAll();
}
public class QueuedPool<T> : Queue<T>, IStore<T>
   {
        public T Fetch()
        {
            return (T)Dequeue();
        }
        public void Store(T obj)
        {
            Enqueue(obj);
        }
        public void ClearAll()
        {
            base.Clear();
        }
}
At client side
QueuedPool<Person> queuePool = new QueuedPool<Person>();
queuePool.Store(new Person());
Person p = queuePool.Fetch();
 
EX: Thread safe Example
public sealed class ObjectPoolObject<T> where T : new()
        {
        private readonly int _poolSize;
        private readonly object _threadLocker;
        private readonly Queue<T> _poolManager;
      
 
        public ObjectPoolObject(int expectedPoolSize)
        {
            if (expectedPoolSize <= 0)
                throw new ArgumentOutOfRangeException("expectedPoolSize", "Pool size can't be null or zero or less than zero");
 
            _poolManager = new Queue<T>();
            _threadLocker = new object();
            _poolSize = expectedPoolSize;
        }
 
        public T Get()
        {
            lock (_threadLocker)
            {
                if (_poolManager.Count > 0)
                {
                     return _poolManager.Dequeue();
                }
                else
                {
                    return new T();
                }
            }
        }
 
        public int Count()
        {
            return _poolManager.Count;
        }
 
        public void Put(T obj)
        {
            lock(_threadLocker)
            {
                if (_poolManager.Count < _poolSize)
                    _poolManager.Enqueue(obj);
            }
         }
    }
At client side
ObjectPoolObject<Person> personPoolObject = new ObjectPoolObject<Person>(10);
Person a = personPoolObject.Get();
Person a1 = personPoolObject.Get();
 
addressPoolObject.Put(a);
addressPoolObject.Put(a1);
Best candidates for
1.       Any ticketing counter, who goes first those, gets ticks first.
2.       Who places order first they get served first.
Now let us continue with other options available in C#
Stack Class
The Stack class implements a Last in First Out data structure. The objects are stored in such a manner that the object added last is placed at the top of the stack.
Push () method adds new item to stack on the top of all items. Pop () method removes the top item in the items list.
 
public class StackPool<T>: Stack<T>, IStore<T>
{
        public T Fetch()
        {
            return Pop();
        }
 
        public void Store(T obj)
        {
            Push(obj);
        }
 
        public void ClearAll()
        {
            Clear();
        }
    }
At client
StackPool<Person> personStackPool = new StackPool<Person>();
 
personStackPool.Store(new Address());
personStackPool.Store(new Address());
 
Person p1 = personStackPool.Fetch();
Person p2 = personStackPool.Fetch();
Singleton Example
 public sealed class ObjectPoolObject<T> where T : new()
    {
        private readonly object _threadLocker = new object();
        private readonly Queue<T> _poolManager = new Queue<T>();
        private static ObjectPoolObject<T> _objectPoolObject;
        private ObjectPoolObject() { }
 
        static ObjectPoolObject()
        {
            _objectPoolObject = new ObjectPoolObject<T>();
        }
 
 
        public static ObjectPoolObject<T> GetInstance()
        {
            return _objectPoolObject;
        }
 
        public T Get()
        {
            lock (_threadLocker)
            {
                if (_poolManager.Count > 0)
                {
                     return _poolManager.Dequeue();
                }
                else
                {
                    return new T();
                }
            }
        }
 
        public int Count()
        {
            return _poolManager.Count;
        }
 
        public void Put(T obj)
        {
            lock(_threadLocker)
            {
                _poolManager.Enqueue(obj);
            }
           
        }
   }
 public class Person
   {
        private string _firstName;
        private string _middleInitial;
        private string _lastName;
      
        public string FirstName
        {
            get { return _firstName;}
            set { _firstName = value; }
        }
        public string MiddleInitial
        {
            get { return _middleInitial;}
            set { _middleInitial = value; }
        }
        public string LastName
        {
            get { return _lastName;}
            set { _lastName = value; }
        }
        public Person() { }
}

Hope this helps

Thanks,

Chinna

 

 
Sign Up to vote for this article
 
About Author
 
Chinna Srihari
Occupation-Software Engineer
Company-
Member Type-Junior
Location-India
Joined date-17 Jun 2010
Home Page-
Blog Page-
Having 12 + years of IT experience, 2.5 years as Technical Management experience and 1.5 year of onsite coordinator experience and rest 8+ years of technical activities including Project Leader, Tech Lead, Designer, PQL, and Developer experience in Quality Management System (CMM-level 5, SEI-CMM-level 5).
 
 
Other popularSectionarticles
    Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
    Published Date : 23/Oct/2010
    This is a quite simple design pattern, let me tell you one thing there are many design patterns that they are implicitly singletons. I rather recommend to understanding this one first before going through other patterns.
    Published Date : 21/Oct/2010
    The Command pattern creates distance between the client that requests an operation and the object that can perform it.
    Published Date : 20/Sep/2010
    Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.
    Published Date : 22/Oct/2010
    A fully initialized instance to be copied or cloned. The Prototype pattern specifies the kind of objects to create using a prototypical instance.
    Published Date : 22/Oct/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top