Class: ConnectionPool::TimedStack

Inherits:
Object
  • Object
show all
Defined in:
lib/connection_pool/timed_stack.rb

Instance Method Summary collapse

Constructor Details

#initialize(size = 0) ⇒ TimedStack

Returns a new instance of TimedStack.



7
8
9
10
11
12
# File 'lib/connection_pool/timed_stack.rb', line 7

def initialize(size = 0)
  @que = Array.new(size) { yield }
  @mutex = Mutex.new
  @resource = ConditionVariable.new
  @shutdown_block = nil
end

Instance Method Details

#clearObject



58
59
60
# File 'lib/connection_pool/timed_stack.rb', line 58

def clear
  @que.clear
end

#empty?Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/connection_pool/timed_stack.rb', line 54

def empty?
  @que.empty?
end

#lengthObject



62
63
64
# File 'lib/connection_pool/timed_stack.rb', line 62

def length
  @que.length
end

#pop(timeout = 0.5) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/connection_pool/timed_stack.rb', line 27

def pop(timeout=0.5)
  deadline = Time.now + timeout
  @mutex.synchronize do
    loop do
      raise ConnectionPool::PoolShuttingDownError if @shutdown_block
      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

#push(obj) ⇒ Object Also known as: <<



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/connection_pool/timed_stack.rb', line 14

def push(obj)
  @mutex.synchronize do
    if @shutdown_block
      @shutdown_block.call(obj)
    else
      @que.push obj
    end

    @resource.broadcast
  end
end

#shutdown(&block) ⇒ Object

Raises:

  • (ArgumentError)


40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/connection_pool/timed_stack.rb', line 40

def shutdown(&block)
  raise ArgumentError, "shutdown must receive a block" unless block_given?

  @mutex.synchronize do
    @shutdown_block = block
    @resource.broadcast

    @que.size.times do
      conn = @que.pop
      block.call(conn)
    end
  end
end