官术网_书友最值得收藏!

Object pool pattern

The instantiation of objects is one of the most costly operations in terms of performance. While in the past this could have been an issue, nowadays we shouldn't be concerned about it. However, when we deal with objects that encapsulate external resources, such as database connections, the creation of new objects becomes expensive.

The solution is to implement a mechanism that reuses and shares objects that are expensive to create. This solution is called the object pool pattern and it has the following structure:

The classes that are used in the object pool pattern are the following:

  • ResourcePool: A class that encapsulates the logic to hold and manage a list of resources.
  • Resource: A class that encapsulates a limited resource. The Resource classes are always referenced by the ResourcePool, so they will never be garbage collected as long as the ResourcePool is not de-allocated.
  • Client: The class that uses resources.

When a Client needs a new Resource, it asks for it from the ResourcePool. The pool checks and takes the first available resource and returns it to the client:

public Resource acquireResource()
{
if ( available.size() <= 0 )
{
Resource resource = new Resource();
inuse.add(resource);
return resource;
}
else
{
return available.remove(0);
}
}

Then, when the Client finishes using the Resource, it releases it. The resource is added back to the tool so that it can be reused.

public void releaseResource(Resource resource)
{
available.add(resource);
}

One of the best examples of resource pooling is database connection pooling. We maintain a pool of database connections and let the code use connections from this pool.

主站蜘蛛池模板: 乌拉特中旗| 建湖县| 岑巩县| 毕节市| 鄂托克前旗| 岑溪市| 济南市| 翁牛特旗| 察雅县| 铁岭县| 仁怀市| 通辽市| 诏安县| 会同县| 丰原市| 新密市| 宁南县| 南宫市| 寿宁县| 原阳县| 沾化县| 罗定市| 凤翔县| 隆子县| 东城区| 军事| 嘉定区| 化德县| 甘德县| 方山县| 许昌市| 新巴尔虎右旗| 潍坊市| 湘阴县| 封丘县| 苍南县| 咸丰县| 沾化县| 高雄市| 开远市| 宁波市|