This article is excerpted from This is How Design Patterns should Be Learned

1 Object pool mode definition

Object Pool Pattern is one of the creation design patterns. After objects are created and initialized in advance, Object providers can use 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 are already initialized and ready to use, and can be created and destroyed as needed. Users of the object pool can retrieve objects from the pool, manipulate them, and return them to the pool when they are no longer needed rather than destroying them. Object pool is a special factory object, object pool pattern is singleton pattern plus share element pattern.

2 Application scenarios of the object pool mode

The object pool mode applies to the following application scenarios.

(1) Resource-constrained scenarios. For example, in environments where scalability is not required (physical resources such as CPU/memory are limited), CPU performance is not strong enough, memory is tight, garbage collection, memory jitter can have a significant impact, memory management efficiency needs to be improved, responsiveness is more important than throughput.

(2) A limited number of objects in memory.

(3) To create objects with high cost, pooling can be considered.

Addendum: Common scenarios for using object pools include various connection pools, thread pools, and database connection pools when using sockets.

UML class diagram for object pool pattern

The UML class diagram for the object pool pattern is shown below.

As you can see from the figure above, the object pool pattern mainly consists of three roles.

(1) ObjectPool: holds objects and provides fetching/returning methods.

(2) abstract PooledObject: abstraction of pooled objects.

(3) ConcretePoolObject: Encapsulates an object in a pool, encapsulating its state and other information.

4 General notation for 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 objects
    interface IPooledObject {
        void operation(a);
    }
    // Specific object
    static class ConcretePoolObject implements IPooledObject {
        public void operation(a) {
            System.out.println("doing"); }}/ / object pool
    static class ObjectPool {
        private int step = 10;  					// The number of objects to be expanded each time when there are not enough objects
        private int minCount;
        private int maxCount;
        private Vector<IPooledObject> returneds; 	// Save unloaned objects
        private Vector<IPooledObject> borroweds; 	// Save the loaned object

        // Initializes the 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 immutable, it is used as the cache key
        public IPooledObject borrowObject(a) {
            IPooledObject next = null;
            if(returneds.size() > 0){
                Iterator<IPooledObject> i = returneds.iterator();
                while (i.hasNext()){
                    next = i.next();
                    returneds.remove(next);
                    borroweds.add(next);
                    returnnext; }}else{
                // Count the number of objects left to create
                int count = (maxCount - minCount);
                // The number of objects that can be created is greater than the number of fixed objects created at a time
                // initializes a fixed number of objects
                refresh(count > step ? step : count);
            }
            return next;
        }

        // Return objects that do not need to be used for reuse
        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(newConcretePoolObject()); }}}}Copy the code

The main difference between the object pooling mode and the share mode is that there is an additional method to reclaim objects for reuse. Therefore, the object pool pattern should be a more specific application scenario of the share pattern. It is equivalent to borrowing objects from the object pool and then returning them to ensure the reuse of limited resources.

5 Advantages and disadvantages of the object pool mode

5.1 the advantages

Reuse objects in the pool, eliminating the memory overhead, CPU overhead, and network overhead generated across the network by creating and reclaiming objects.

5.2 disadvantages

(1) Increased overhead of allocating/releasing objects.

(2) In a concurrent environment, multiple threads may need to acquire objects from the pool, need to synchronize on the heap data structure or block due to lock contention, which can be hundreds of times more expensive than 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 set the size of the object pool reasonably. If it is too small, it will not work; If the memory usage is too large, the memory usage is too high. Pay attention to “Tom play architecture” reply to “design pattern” can obtain the complete source code.

Tom play architecture: 30 real cases of design patterns (attached source code), the challenge of annual salary 60W is not a dream

This article is “Tom play structure” original, reproduced please indicate the source. Technology is to share, I share my happiness! If this article is helpful to you, welcome to follow and like; If you have any suggestions can also leave a comment or private letter, your support is my motivation to adhere to the creation. Pay attention to “Tom bomb architecture” for more technical dry goods!