Class: Legion::Transport::Helpers::Pool
- Inherits:
-
Object
- Object
- Legion::Transport::Helpers::Pool
- Defined in:
- lib/legion/transport/helpers/pool.rb
Instance Method Summary collapse
- #checkin(connection) ⇒ Object
- #checkout ⇒ Object
- #connected? ⇒ Boolean
-
#initialize(size: 1, timeout: 5, &block) ⇒ Pool
constructor
A new instance of Pool.
- #shutdown ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize(size: 1, timeout: 5, &block) ⇒ Pool
Returns a new instance of Pool.
7 8 9 10 11 12 13 14 15 |
# File 'lib/legion/transport/helpers/pool.rb', line 7 def initialize(size: 1, timeout: 5, &block) @size = size @timeout = timeout @factory = block @available = [] @in_use = [] @mutex = Mutex.new @condition = ConditionVariable.new end |
Instance Method Details
#checkin(connection) ⇒ Object
49 50 51 52 53 54 55 56 |
# File 'lib/legion/transport/helpers/pool.rb', line 49 def checkin(connection) @mutex.synchronize do @in_use.delete(connection) @available << connection if connection.respond_to?(:open?) && connection.open? Legion::Logging.debug "Pool checkin (available=#{@available.size} in_use=#{@in_use.size})" if defined?(Legion::Logging) @condition.signal end end |
#checkout ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/legion/transport/helpers/pool.rb', line 17 def checkout deadline = Time.now + @timeout @mutex.synchronize do loop do @available.reject! { |c| c.respond_to?(:closed?) && c.closed? } if (conn = @available.pop) @in_use << conn Legion::Logging.debug "Pool checkout (available=#{@available.size} in_use=#{@in_use.size})" if defined?(Legion::Logging) return conn end total = @available.size + @in_use.size if total < @size conn = @factory.call @in_use << conn Legion::Logging.debug "Pool checkout new connection (available=#{@available.size} in_use=#{@in_use.size})" if defined?(Legion::Logging) return conn end remaining = deadline - Time.now if remaining <= 0 Legion::Logging.warn "Pool timeout after #{@timeout}s (size=#{@size} in_use=#{@in_use.size})" if defined?(Legion::Logging) raise Legion::Transport::PoolTimeout, 'timed out waiting for available connection' end @condition.wait(@mutex, remaining) end end end |
#connected? ⇒ Boolean
74 75 76 77 78 |
# File 'lib/legion/transport/helpers/pool.rb', line 74 def connected? @mutex.synchronize do (@available + @in_use).any? { |c| c.respond_to?(:open?) && c.open? } end end |
#shutdown ⇒ Object
62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/legion/transport/helpers/pool.rb', line 62 def shutdown @mutex.synchronize do (@available + @in_use).each do |conn| conn.close rescue StandardError => e Legion::Logging.debug("Pool#shutdown connection close failed: #{e.}") if defined?(Legion::Logging) end @available.clear @in_use.clear end end |
#size ⇒ Object
58 59 60 |
# File 'lib/legion/transport/helpers/pool.rb', line 58 def size @mutex.synchronize { @available.size + @in_use.size } end |