Class: Squirm::Pool

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/squirm/pool.rb

Overview

A ridiculously simple object pool.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timeout = 5) ⇒ Pool

Returns a new instance of Pool.



17
18
19
20
21
22
23
# File 'lib/squirm/pool.rb', line 17

def initialize(timeout=5)
  @mutex       = Monitor.new
  @timeout     = timeout
  @condition   = @mutex.new_cond
  @queue       = []
  @connections = Set.new
end

Instance Attribute Details

#connectionsObject (readonly)

Returns the value of attribute connections.



12
13
14
# File 'lib/squirm/pool.rb', line 12

def connections
  @connections
end

#timeoutObject

Returns the value of attribute timeout.



13
14
15
# File 'lib/squirm/pool.rb', line 13

def timeout
  @timeout
end

Instance Method Details

#checkin(conn) ⇒ Object

Check out a connection.



40
41
42
43
44
45
46
# File 'lib/squirm/pool.rb', line 40

def checkin(conn)
  synchronize do
    @connections.add conn
    @queue.push conn
    @condition.signal
  end
end

#checkoutObject

Check a connection back in.



31
32
33
34
35
36
37
# File 'lib/squirm/pool.rb', line 31

def checkout
  synchronize do
    return @queue.shift unless @queue.empty?
    @condition.wait(@timeout)
    @queue.empty? ? raise(Timeout) : next
  end
end

#each(&block) ⇒ Object

Synchronizes iterations provided by Enumerable.



26
27
28
# File 'lib/squirm/pool.rb', line 26

def each(&block)
  synchronize { @connections.each(&block) }
end