Class: Griffin::ConnectionPool::Pool

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

Constant Summary collapse

DEFAULTS =
{ size: 5, timeout: 5 }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, &block) ⇒ Pool

Returns a new instance of Pool.

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/griffin/connection_pool/pool.rb', line 12

def initialize(options = {}, &block)
  raise ArgumentError, 'Connection pool requires a block' unless block

  options = DEFAULTS.merge(options)

  @size = Integer(options.fetch(:size))
  @timeout = Integer(options.fetch(:timeout))

  @available = Griffin::ConnectionPool::MultiTimedStack.new(@size, &block)
  @key = :"current-#{@available.object_id}"
  Thread.current[@key] = Hash.new { |h, k| h[k] = [] }
end

Instance Method Details

#checkin(key) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/griffin/connection_pool/pool.rb', line 25

def checkin(key)
  stack = Thread.current[@key][key]
  raise 'no connections are checked out' if stack.empty?

  conn = stack.pop
  if stack.empty?
    @available.push(conn, connection_args: key)
  end
  nil
end

#checkout(key) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/griffin/connection_pool/pool.rb', line 36

def checkout(key)
  stack = Thread.current[@key][key]

  conn =
    if stack.empty?
      @available.pop(connection_args: key)
    else
      stack.last
    end

  stack.push(conn)

  conn
end

#shutdown(&block) ⇒ Object



51
52
53
# File 'lib/griffin/connection_pool/pool.rb', line 51

def shutdown(&block)
  @available.shutdown(&block)
end