Class: MultiThink

Inherits:
Object
  • Object
show all
Defined in:
lib/multithink.rb,
lib/multithink/version.rb

Defined Under Namespace

Classes: Connection, PoolShuttingDownError, TimedStack

Constant Summary collapse

DEFAULTS =
{size: 5, timeout: 5, servers: [{host: '127.0.0.1', port: 28015}]}
VERSION =
"0.0.3"

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ MultiThink

Returns a new instance of MultiThink.



7
8
9
10
11
12
13
14
15
16
# File 'lib/multithink.rb', line 7

def initialize(options = {})
  options = DEFAULTS.merge(options)

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

  @available = TimedStack.new(@size, @servers)
  @key = :"current-#{@available.object_id}"
end

Instance Method Details

#checkinObject



41
42
43
44
45
46
47
48
# File 'lib/multithink.rb', line 41

def checkin
  stack = ::Thread.current[@key]
  conn = stack.pop
  if stack.empty?
    @available << conn
  end
  nil
end

#checkout(options = {}) ⇒ Object



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

def checkout(options = {})
  stack = ::Thread.current[@key] ||= []

  if stack.empty?
    timeout = options[:timeout] || @timeout
    conn = @available.pop(timeout)
  else
    conn = stack.last
  end

  stack.push conn
  conn
end

#shutdownObject



50
51
52
# File 'lib/multithink.rb', line 50

def shutdown
  @available.shutdown
end

#with(options = {}) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/multithink.rb', line 18

def with(options = {})
  conn = checkout(options)
  begin
    yield conn
  ensure
    checkin
  end
end