Filed under: General, Programming, .NET — Oliver Sturm @ 10:16 am - 2 years, 11 months ago
This is the sixth article in my mini series about object pooling. Be sure to read part 1, part 2, part 3, part 4 and part 5 first.
It took me a while to find the time for the next article, but here it is. Now we’re finally going to deal with the topic of growing and shrinking the pool.
One of the first questions we have to ask when it comes to this is, when are we going to do it? We have one mechanism for growing the pool implemented already, which takes place when, during a call to the GetObject method, no unused object can be found in the pool. But is this the right place to think about growing, really? And what about shrinking?
I think it’s a good idea to keep these things out of the way of “normal call flow”. Meaning, if possible, a client’s call to get an object from the pool shouldn’t be delayed by management work. So I have implemented the mechanism with the help of a timer: a regular check is executed to find whether the number of used objects in the pool is too high or too low and growing or shrinking is done accordingly.
To classify the number of used objects as “too high” or “too low”, I’ve introduced two properties “HighWaterMark” and “LowWaterMark”. These are percentage values: if the percentage of used objects in the pool is higher than HighWaterMark, the pool is considered too small and vice versa. To prevent the pool size from being scaled up and down wildly in certain scenarios, I have also introduced threshold values - so the percentage has to be found to be too high at more than one check in a row, for example, for the pool to be grown. Actually, the threshold is more useful in the shrinking than the growing case, but it’s the same principle.
So, here’s the code for these changes. The next article will introduce a sample program to test all the functionality that’s implemented so far and I’ll post the source code for the pool and the sample with it. So if you haven’t been typing in all this code yourself, stay tuned for the next installment in the series!