Object Pool Pattern

This article is excerpted from "design patterns should be learned this way"

1 definition of object pool mode

Object Pool Pattern is a kind of creative design pattern. After objects are created and initialized in advance and put into the object pool, the object provider can use the existing objects to process requests, reducing the memory space and initialization time occupied by frequent object creation.
An object pool contains a set of objects that have been initialized and can be used. Objects can be created and destroyed when needed. Users of the object pool can get objects from the pool, operate them, and return them to the pool when they are not needed, rather than destroy them directly. Object pool is a special factory object. Object pool mode is singleton mode plus meta mode.

2. Application scenario of object pool mode

The object pool mode is mainly applicable to the following application scenarios.

(1) Resource constrained scenarios. For example, in an environment that does not require scalability (CPU \ memory and other physical resources are limited), CPU performance is not strong enough, memory is tight, garbage collection and memory jitter will have a great impact, so memory management efficiency needs to be improved, and responsiveness is more important than throughput.

(2) A limited number of objects in memory.

(3) To create objects with high cost, you can consider pooling.

Add: common scenarios of using object pool include various connection pools, thread pools, database connection pools, etc. when using Socket.

3 UML class diagram of Object Pool Pattern

The UML class diagram of the object pool pattern is shown in the following figure.

As can be seen from the above figure, the object pool mode mainly includes three roles.

(1) Object pool: holds objects and provides methods such as fetch / return.

(2) PooledObject: the abstraction of objects in the pool.

(3) Concrete poolobject: encapsulates the objects in the pool, encapsulates the state of the objects and some other information.

4 general writing method of object pool mode

The following is a common way to write the object pool pattern.

public class Client {

    public static void main(String[] args) {
        ObjectPool pool = new ObjectPool(10,50);
        IPooledObject object = pool.borrowObject();
        object.operation();
        pool.returnObject(object);
        System.out.println();
    }

    //Abstract object
    interface IPooledObject {
        void operation();
    }
    //Specific object
    static class ConcretePoolObject implements IPooledObject {
        public void operation() {
            System.out.println("doing");
        }
    }

    //Object pool
    static class ObjectPool {
        private int step = 10;                      //When the objects are not enough, the quantity of each expansion
        private int minCount;
        private int maxCount;
        private Vector<IPooledObject> returneds;     //Save objects not lent
        private Vector<IPooledObject> borroweds;     //Save objects that have been lent out

        //Initialize object pool
        public ObjectPool(int minCount,int maxCount){
            borroweds = new Vector<IPooledObject>();
            returneds = new Vector<IPooledObject>();

            this.minCount = minCount;
            this.maxCount = maxCount;

            refresh(this.minCount);
        }

        //Because the internal state is invariant, it is used as the key of cache
        public IPooledObject borrowObject() {
            IPooledObject next = null;
            if(returneds.size() > 0){
                Iterator<IPooledObject> i = returneds.iterator();
                while (i.hasNext()){
                    next = i.next();
                    returneds.remove(next);
                    borroweds.add(next);
                    return next;
                }
            }else{
                //Calculate the number of remaining objects that can be created
                int count = (maxCount - minCount);
                //The remaining number of objects that can be created is greater than the number of objects created in a single fix
                //Then initialize a fixed number of objects
                refresh(count > step ? step : count);
            }
            return next;
        }

        //Return and reuse objects that do not need to be used
        public void returnObject(IPooledObject pooledObject){
            returneds.add(pooledObject);
            if(borroweds.contains(pooledObject)){
                borroweds.remove(pooledObject);
            }
        }

        private void refresh(int count){
            for (int i = 0; i < count; i++) {
                returneds.add(new ConcretePoolObject());
            }
        }
    }
}

The biggest difference between the object pool mode and the shared element mode is that there will be an additional method for recycling objects in the object pool mode. Therefore, the object pool pattern should be a more specific application scenario of the shared meta pattern. It is equivalent to lending objects from the object pool and returning them after they are used up, so as to ensure the reuse of limited resources.

5 advantages of object pool mode

Reuse the objects in the pool to eliminate the memory overhead, CPU overhead and network overhead caused by creating and recycling objects.

6 disadvantages of object pool mode

(1) Increases the overhead of allocating / releasing objects.

(2) In a concurrent environment, multiple threads may need to acquire objects in the pool (at the same time), and then need to synchronize on the heap data structure or block due to lock competition. This overhead is hundreds of times higher than the overhead of creating and destroying objects.

(3) Due to the limited number of objects in the pool, it is bound to become a scalability bottleneck.

(4) It is difficult to reasonably set the size of the object pool. If it is too small, it will not work; If it is too large, it will occupy high memory resources.

Focus on WeChat's official account of Tom architecture and reply to the "design pattern" to get the complete source code.

[recommendation] Tom bomb architecture: 30 real cases of design patterns (with source code attached). Challenging the annual salary of 60W is not a dream

This article is the original of "Tom bomb architecture". Please indicate the source for reprint. Technology lies in sharing, I share my happiness!
If this article is helpful to you, you are welcome to pay attention and praise; If you have any suggestions, you can also leave comments or private letters. Your support is the driving force for me to adhere to my creation. Focus on WeChat official account Tom structure, get more dry cargo!

Keywords: Java Design Pattern architecture

Added by quadlo on Thu, 25 Nov 2021 22:32:40 +0200