class ResourcePool

Attributes

allocated[R]
max_size[R]
pool[R]

Public Class Methods

new(opts={}, &block) click to toggle source
# File lib/resource_pool.rb, line 8
def initialize(opts={}, &block)
  @max_size = opts[:max_size] || 4
  @create_proc = block
  @pool = []
  @allocated = {}
  @mutex = Mutex.new
  @timeout = opts[:pool_timeout] || 2
  @sleep_time = opts[:pool_sleep_time] || 0.001
  @delete_proc = opts[:delete_proc]
end

Public Instance Methods

hold() { |res| ... } click to toggle source
# File lib/resource_pool.rb, line 31
def hold
  t = Thread.current
  if res = owned_resource(t)
    return yield(res)
  end

  begin
    unless res = acquire(t)
      raise ResourceNotAvailable if @timeout == 0
      time = Time.now
      timeout = time + @timeout
      sleep_time = @sleep_time
      sleep sleep_time
      until res = acquire(t)
        raise ResourceNotAvailable if Time.now > timeout
        sleep sleep_time
      end
    end
    yield res
  ensure
    sync{release(t)} if owned_resource(t)
  end
end
release_all(&block) click to toggle source
# File lib/resource_pool.rb, line 23
def release_all(&block)
  block ||= @delete_proc
  sync do
    @pool.each{|res| block.call(res)} if block
    @pool.clear
  end
end
size() click to toggle source
# File lib/resource_pool.rb, line 19
def size
  @allocated.length + @pool.length
end
trash_current!() click to toggle source

please only call this inside hold block

# File lib/resource_pool.rb, line 56
def trash_current!
  t    = Thread.current
  conn = owned_resource(t)
  return unless conn

  @delete_proc.call conn if @delete_proc
  sync { @allocated.delete(t) }
  nil
end

Private Instance Methods

acquire(thread) click to toggle source
# File lib/resource_pool.rb, line 72
def acquire(thread)
  sync do
    res = available
    @allocated[thread] = res if res
  end
end
available() click to toggle source
# File lib/resource_pool.rb, line 83
def available
  @pool.pop || make_new
end
create_resource() click to toggle source
# File lib/resource_pool.rb, line 96
def create_resource
  resource = @create_proc.call
  raise InvalidCreateProc, "create_proc returned nil" unless resource
  resource
end
make_new() click to toggle source
# File lib/resource_pool.rb, line 87
def make_new
  salvage if size >= @max_size
  size < @max_size ? create_resource : nil
end
owned_resource(thread) click to toggle source
# File lib/resource_pool.rb, line 68
def owned_resource(thread)
  sync{ @allocated[thread] }
end
release(thread) click to toggle source
# File lib/resource_pool.rb, line 79
def release(thread)
  @pool << @allocated.delete(thread)
end
salvage() click to toggle source
# File lib/resource_pool.rb, line 92
def salvage
  @allocated.keys.each{ |t| release(t) unless t.alive? }
end
sync() { || ... } click to toggle source
# File lib/resource_pool.rb, line 102
def sync
  @mutex.synchronize{yield}
end