Ruby Common Object Pool (common-pool)
A few months ago, when I migrated BookJetty from Java to Ruby On Rails (RoR) platform, one obstacle I faced was I could not find any object pooling library that checks for idle objects on a fixed interval, and evicts invalid and expired objects in the pool.
While in Java I used Apache Commons Pool, in Ruby, I was scratching my head back then.
But, the beauty of Ruby-and-Rails world is the citizen love to hack, when they can’t find a way, well, they always hack a way out. So being a good citizen wannabe, I wrote the Ruby version of first-in-first-out (FIFO) object pool library inspired by Apache Commons Pool.
It currently supports the following configuration parameters:
- min_idle
- max_idle
- max_idle_time
- max_active
- timeout
- validation_timeout
- idle_check_no_per_run
- idle_check_interval
This morning I’ve just got the time to wrap it up as a gem. To get started:
$ gem install common-pool
And some code snippets:
require 'common_pool'
# Extend data source object
class RandomNumberDataSource < CommonPool::PoolDataSource
# Overwrite to return object to be stored in the pool.
def create_object
rand(1000)
end
# Overwrite to check if idle object in the pool is still valid.
def valid?(object)
true
end
end
# Create a new object pool
object_pool = ObjectPool.new(RandomNumberDataSource.new)
# Borrow object from the pool
object = object_pool.borrow_object
# Return object to the pool
object_pool.return_object(object)
# Or invalidate object and remove it from the pool
object_pool.invalidate_object(object)
# Create object pool with idle objects eviction thread
object_pool = ObjectPool.new(RandomNumberDataSource.new) do |config|
config.min_idle = 5
config.max_idle = 10
# max 10 idle objects checked per run
config.idle_check_no_per_run = 10
# check idle objects every 10 minutes
config.idle_check_interval = 10 * 60
end
# Return a hash of pool instance status variables, i.e.
# active and idle lists size, and configuration options
object_pool.status_info
For more information, visit common-pool rdoc documentation.

Add Your Comment