Class: Legion::Transport::Helpers::Pool
- Inherits:
-
Object
- Object
- Legion::Transport::Helpers::Pool
- Includes:
- Logging::Helper
- 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.
11 12 13 14 15 16 17 18 19 |
# File 'lib/legion/transport/helpers/pool.rb', line 11 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
53 54 55 56 57 58 59 60 |
# File 'lib/legion/transport/helpers/pool.rb', line 53 def checkin(connection) @mutex.synchronize do @in_use.delete(connection) @available << connection if connection.respond_to?(:open?) && connection.open? log.debug "Pool checkin (available=#{@available.size} in_use=#{@in_use.size})" @condition.signal end end |
#checkout ⇒ Object
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 48 49 50 51 |
# File 'lib/legion/transport/helpers/pool.rb', line 21 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 log.debug "Pool checkout (available=#{@available.size} in_use=#{@in_use.size})" return conn end total = @available.size + @in_use.size if total < @size conn = @factory.call @in_use << conn log.debug "Pool checkout new connection (available=#{@available.size} in_use=#{@in_use.size})" return conn end remaining = deadline - Time.now if remaining <= 0 log.warn "Pool timeout after #{@timeout}s (size=#{@size} in_use=#{@in_use.size})" raise Legion::Transport::PoolTimeout, 'timed out waiting for available connection' end @condition.wait(@mutex, remaining) end end end |
#connected? ⇒ Boolean
79 80 81 82 83 |
# File 'lib/legion/transport/helpers/pool.rb', line 79 def connected? @mutex.synchronize do (@available + @in_use).any? { |c| c.respond_to?(:open?) && c.open? } end end |
#shutdown ⇒ Object
66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'lib/legion/transport/helpers/pool.rb', line 66 def shutdown @mutex.synchronize do (@available + @in_use).each do |conn| conn.close rescue StandardError => e handle_exception(e, level: :warn, handled: true, operation: 'transport.pool.shutdown', size: @size) end @available.clear @in_use.clear end log.info "Pool shutdown complete size=#{@size}" end |
#size ⇒ Object
62 63 64 |
# File 'lib/legion/transport/helpers/pool.rb', line 62 def size @mutex.synchronize { @available.size + @in_use.size } end |