Sha256: 020f051606f3580b94706edbb1efae62cf664c763ac3eefc4906f425d8007db8

Contents?: true

Size: 752 Bytes

Versions: 3

Compression:

Stored size: 752 Bytes

Contents

require 'thread'
require 'timeout'

class ConnectionPool::TimedStack
  def initialize(size = 0)
    @que = Array.new(size) { yield }
    @mutex = Mutex.new
    @resource = ConditionVariable.new
  end

  def push(obj)
    @mutex.synchronize do
      @que.push obj
      @resource.broadcast
    end
  end
  alias_method :<<, :push

  def pop(timeout=0.5)
    deadline = Time.now + timeout
    @mutex.synchronize do
      loop do
        return @que.pop unless @que.empty?
        to_wait = deadline - Time.now
        raise Timeout::Error, "Waited #{timeout} sec" if to_wait <= 0
        @resource.wait(@mutex, to_wait)
      end
    end
  end

  def empty?
    @que.empty?
  end

  def clear
    @que.clear
  end

  def length
    @que.length
  end
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
sidekiq-statsd-0.1.1 vendor/ruby/1.9.1/gems/connection_pool-1.0.0/lib/connection_pool/timed_stack.rb
sidekiq-statsd-0.1.0 vendor/ruby/1.9.1/gems/connection_pool-1.0.0/lib/connection_pool/timed_stack.rb
connection_pool-1.0.0 lib/connection_pool/timed_stack.rb