Evgenii Legotckoi
Evgenii LegotckoiSept. 18, 2018, 4:01 a.m.

Generative Design Patterns - Object Pool

Goals

Object pooling can greatly improve performance; it is most effective in situations where the cost of initializing an instance of a class is high and the rate of instantiation of the class is high, while the number of instances in use at any given time is small.

Problems

Object pools (otherwise known as resource pools) are used to manage object caching. A client that has access to an object pool can avoid creating new objects by simply asking the pool for a new object that has already been created. Typically, a pool will be a growing pool, i.e. the pool itself will create new objects if the pool is empty. We can also have a pool that limits the number of objects created.

It is desirable to keep all reusable objects that are not currently in use in the same object pool so that they can be managed by one consistent policy. To achieve this, the reusable pool class must implement the Singleton design pattern.


Discussion

The object pool allows other objects to "check" objects from their pool, when those objects are no longer needed by their processes, they are returned to the pool for reuse.

However, we don't want the process to have to wait for a particular object to be allocated, so the object pool also creates new objects as needed, but also needs to use a facility to periodically clean up unused objects.

Structure

The general idea of the connection pool pattern is that if class instances can be reused, then you avoid creating class instances by reusing them.

  • Reusable . Instances of classes in this role interact with other objects for a limited period of time, after which they are no longer needed for this collaboration.
  • Client . Class instances in this role use reusable objects.
  • ReusablePool. Class instances in this role manage reusable objects for use by Client objects.

It is generally desirable to keep all reusable objects that are not currently in use in the same object pool so that they can be managed by one consistent policy. Therefore the ReusablePool class is for the Singleton class. Its constructor(s) are private, which forces other classes to call the getInstance method to get the same instance of the ReusablePool class.

The Client object calls the acquireReusable method of the ReusablePool object when it needs a reusable object. The ReusablePool object maintains a collection of reusable objects. It uses a collection of reusable objects to contain a pool of reusable objects that are not currently in use.

If there are any reusable objects in the pool, when the acquireReusable method is called, it removes the Reusable object from the pool and returns it. If the pool is empty, the acquireReusable method creates a reusable object if possible. If the acquireReusable method cannot create a new reusable object, it waits until the collection object is returned to the collection again.

Client objects pass a reusable object to the releaseReusable method on the ReusablePool when they have finished working with the object. The releaseReusable method returns a reusable object to a pool of reusable objects that are not being used.

In many applications, the object pool design pattern has reasons for limiting the total number of reusable objects that can exist. In such cases, the ReusablePool object that creates reusable objects is responsible for ensuring that it does not create more objects than the specified maximum number of reusable objects. If ReusablePool objects are responsible for limiting the number of objects that are created, then the ReusablePool class will have a method to specify the maximum number of objects that will be created. This method is listed in the diagram above as setMaxPoolSize.

Example

An object pool is similar to an office warehouse. When a new employee is hired, the office manager must prepare a workplace for him. It calculates whether there is spare equipment in the warehouse of the office. If so, then the office manager uses it. If not, it places an order to purchase new equipment from Amazon. In the event that an employee is fired, his equipment is moved to a warehouse where it can be taken when a new workplace is needed.

Control List

  1. Create an ObjectPool class with a private array of objects inside
  2. Create acquire and release methods
  3. Make sure the ObjectPool will work as a singleton

Rules of thumb

  • The Factory Method pattern can be used to encapsulate object creation logic. However, after they are created, it does not manage them, the object pool pattern keeps track of the objects it creates.
  • Pel objects are usually implemented as a singleton
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
AD

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:80points,
  • Rating points4
m

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:20points,
  • Rating points-10
Last comments
ИМ
Игорь МаксимовNov. 22, 2024, 11:51 a.m.
Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
Evgenii Legotckoi
Evgenii LegotckoiOct. 31, 2024, 2:37 p.m.
Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
A
ALO1ZEOct. 19, 2024, 8:19 a.m.
Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Игорь МаксимовOct. 5, 2024, 7:51 a.m.
Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas5July 5, 2024, 11:02 a.m.
QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Now discuss on the forum
Evgenii Legotckoi
Evgenii LegotckoiJune 24, 2024, 3:11 p.m.
добавить qlineseries в функции Я тут. Работы оень много. Отправил его в бан.
t
tonypeachey1Nov. 15, 2024, 6:04 a.m.
google domain [url=https://google.com/]domain[/url] domain [http://www.example.com link title]
NSProject
NSProjectJune 4, 2022, 3:49 a.m.
Всё ещё разбираюсь с кешем. В следствии прочтения данной статьи. Я принял для себя решение сделать кеширование свойств менеджера модели LikeDislike. И так как установка evileg_core для меня не была возможна, ибо он писался…
9
9AnonimOct. 25, 2024, 9:10 a.m.
Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

Follow us in social networks