Class: Upfluence::Pool

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

Defined Under Namespace

Classes: NoInstanciationBlock, UnknownResource

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Pool.



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

def initialize(size = 0, options = {}, &block)
  raise NoInstanciationBlock unless block

  @create_block = block
  @redeemed = []
  @que = []
  @max = size
  @mutex = Mutex.new
  @resource = ConditionVariable.new
  @shutdown_block = nil
  @timeout = options.fetch :timeout, 5
end

Instance Attribute Details

#maxObject (readonly)

Returns the value of attribute max.



9
10
11
# File 'lib/upfluence/pool.rb', line 9

def max
  @max
end

Instance Method Details

#discard(obj) ⇒ Object



24
25
26
27
28
29
# File 'lib/upfluence/pool.rb', line 24

def discard(obj)
  @mutex.synchronize do
    remove_from_redeemed obj
    @resource.broadcast
  end
end

#empty?Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/upfluence/pool.rb', line 58

def empty?
  (@redeemed.length - @que.length) >= @max
end

#lengthObject



62
63
64
# File 'lib/upfluence/pool.rb', line 62

def length
  @max - @redeemed.length + @que.length
end

#pop(options = {}) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/upfluence/pool.rb', line 40

def pop(options = {})
  timeout = options.fetch :timeout, @timeout
  deadline = Time.now + timeout

  @mutex.synchronize do
    loop do
      return redeem(@que.pop) unless @que.empty?

      connection = redeem(try_create(options))
      return connection if connection

      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



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

def push(obj)
  @mutex.synchronize do
    remove_from_redeemed obj

    @que.push obj
    @resource.broadcast
  end
end