This is the fifth article in my mini series about object pooling. Be sure to read part 1, part 2, part 3 and part 4 first.
This part is going to make some modifications to the code in the GetObject() method to implement various alternative behaviours there. Think about it: what do you want to happen if there’s no free object to be had in the pool? I came up with the following possible options:
Return null. In this case, the caller would have to deal with the problem further if it can’t get a pool object.
Throw an exception. Really just a variant of (1), because it also pushes the problem out to the caller.
Try again. Because objects are being used and returned to the pool all the time, it might make sense just to wait a bit and try to allocate an object one more time… or two more times, even. A maximum number of tries would be good, I guess.
Extend the pool. The general growing/shrinking discussion hasn’t taken place yet in these articles, but possibly the case where no more objects are available would be a good place to grow the pool.
Consider this changed code for the GetObject() method:
As you can see, the whole getting-an-object algorithms is potentially repeated multiple times now, possibly sleeping or trying pool extension in between. Finally, when a specific maximum number of retries has run out, an exception is thrown. I’ve specifically decided to do this instead of returning null - I’m assuming there might be no special code to handle null returns on the caller side, otherwise the pool could have been configured to return null in the first place.
The next interesting thing is the ExtendPool() method, which looks like this:
Several properties have been added to the pool to support the new functionality and there’s also an enum for the out of objects behaviour. If you’ve been following the articles closely, you may have noticed that the maxPoolSize had already creapt in to the ExtendPoolBy() method last time, although I hadn’t introduced it yet Here it is now:
Sorry I still didn’t make it to the growing/shrinking, at least not completely. Well, next time!
[…] This is the seventh article in my mini series about object pooling. Be sure to read part 1, part 2, part 3, part 4, part 5 and part 6 first. […]
Pingback by Oliver Sturm’s weblog - Object pooling, part 7 - the first test program — 25/9/2005 @ 4:04 pm - 3 years ago