1.Origin:
The object pool should be a "historical" concept, such as the thread pool we often say, andAdo. netAll applications in the object pool.
Our applications sometimes encounter the need to use the object pool. Let me give an example. Assume that we need to record a classMyclassEach method is called every time the method is executed, and this class is used in a multi-threaded environment, each method can be executed in multiple threads at the same time, no need to be synchronized. This maximizes the concurrency.
good, we can use stopwatch how to use this class to accurately record the time of each method? myclass define a stopwatch type member variable, then, the Start to start the timer, record the time consumed before the method is returned, and then Reset stopwatch member.
This solution can work well only in one situation, that is, it requiresMyclassAnd multiple threads Must BeSynchronization, Otherwise,StopwatchThe timing will be disordered.
So how can this problem be solved? It's actually very simple. We don't need Myclass Define Stopwatch Type member variables, but at the entrance of each method, New One Stopwatch Type of local variable. This local variable serves only one call of the current method. That is to say Myclass Any call to any method Stopwatch The type of object is used for timing the call. When this call returns Stopwatch The object can be destroyed. In this way, we can meet our initial assumptions.
from the solution, a new stopwatch object. When a call returns, this object has no value and can be destroyed. The result is repeatedly created and destroyed stopwatch type object.
This is a perfect place to use the object pool. We recommend some available stopwatch put the object into the object pool. Each time a method is called, to the object pool rent One stopwatch when an object is called for timing, the object return to the object pool. This avoids stopwatch duplicate object creation and destruction.
I designedEsbasic. objectmanagement. Pool. iobjectpoolIs a general object pool, which is generic, so different types of objects can be stored in pools.
2.Applicable scenarios:
Based on the above description, we can conclude that object pool technology can be used when there are requirements similar to the following.
(1)A type of objectOften repeated.
(2)The time when each type of object is usedVery short.
(3)A shared object cannot meet the requirements of the system (for example, it limits the maximum concurrency ).
(4)Compared with creating or destroying an object, it is much easier to clear the object state.
3Design ideas and implementation
IobjectpoolThe interface is defined as follows:
Public Interface Iobjectpool < Tobject > Where Tobject: Class
{
/// <Summary>
/// Minobjectcount: the minimum number of objects that exist in the object pool simultaneously.
/// </Summary>
Int Minobjectcount { Get ; Set ;}
//
// maximum number of objects in the maxobjectcount Object pool simultaneously.
//
int maxobjectcount { Get ; set ;}
/// <Summary>
/// Detectspaninmsecs when there are no idle objects in the pool and the number of objects has reached maxobjectcount, if a rent call occurs at this time, the interval between idle objects is detected.
/// The default value is 10 ms.
/// </Summary>
Int Detectspaninmsecs { Get ; Set ;}
/// <Summary>
/// Pooledobjectcreator is used to create the object creator in the pool. The default value is defaultpooledobjectcreator.
/// </Summary>
Ipooledobjectcreator < Tobject > Pooledobjectcreator { Set ;}
VoidInitialize ();
Tobject rent ();
VoidGiveback (tobject OBJ );
}
This interface has a generic parameter:TobjectIndicates the type of the object to be pooled. Generic constraints indicate that the objects that can be put into the object pool must be of the reference type.
MinobjectcountAttribute indicates that the object pool must ensure the number of objects in the pool during initialization.
MaxobjectcountAttribute indicates the maximum number of objects that the object pool can accommodate.
If an object is rented out, the object pool marks its status as "busy". If an object is not rented out or returned, the status is "idle.
ForObjectpoolNote the following:
(1)The object pool is safe and can be used in a multi-threaded environment. We lock the internal set.
(2) the object pool is not directly responsible for object creation, it delegates this responsibility to the pooled Object Creator ipooledobjectcreator .
(3) pooled Object Creator ipooledobjectcreator not only creates objects, it is also responsible for clearing the object status ( re Set method ). In giveback Reset to clear the legacy state of an object. The ipooledobjectcreator interface is defined as follows:
/// <Summary>
///Ipooledobjectcreator pooling object creators. Used to create objects cached by the pool. And clears the object status.
/// </Summary>
Public Interface Ipooledobjectcreator < Tobject > Where Tobject: Class
{
Tobject create ();
Void Reset (tobject OBJ );
}
4.Precautions for use
(1) when an external call rent when a method rent an object from an object pool, if no "idle" object exists in the object pool and the number of objects in the pool has reached Maxobjectcount ? objectpool the policy is to choose to wait until an object changes to" idle ". Otherwise, the current thread is blocked. You must note that objectpool this policy may be different from your expectation.
(2)When there are many idle objects in the object poolMinobjectcountThe object pool does not release some of the objects, but keeps them.MinobjectcountIt only determines the number of objects that should be created in the pool during initialization to be used for backup.
(3)Based on the two reasons above, we need to be careful when using specific applicationsMaxobjectcountSet a reasonable value. If this value is too small, thread blocking may occur frequently. Of course, this value is not set to a larger value as the better, because if there are many idle objects at ordinary times, it means that you need to occupy more resources, but do not play the corresponding value.
(4)When an object lent out from the pool is returned to the pool, the remaining State must be cleared. Otherwise, the remaining State may be misused.
(5)If it is not easy to clear the state of an object, but it is easy to create and destroy an object, you can consider not using the object pool, but every timeNewWhen an object is used, it is discarded.
5.Extension
If the object to be pooled is stateless and its type also has a default constructor without parameters, we can directly useEsbasicProvided default pooled Object CreatorDefaultpooledobjectcreator.DefaultpooledobjectcreatorUse reflection to create an object andResetMethod does not provide any action for the object-because the object itself is stateless, there is no need to clear its State.
Note: The esbasic source code can be foundHttp://esbasic.codeplex.com/Download.
Esbasic open source Preface