Class: Oedipus::Connection::Pool
- Inherits:
-
Object
- Object
- Oedipus::Connection::Pool
- Defined in:
- lib/oedipus/connection/pool.rb
Overview
Provides a thread-safe pool of connections, with a specified TTL.
Instance Method Summary collapse
-
#acquire ⇒ Object
Acquire a connection from the pool, for the duration of a block.
-
#dispose ⇒ Object
Dispose all connections in the pool.
-
#empty? ⇒ Boolean
Returns true if the pool is currently empty.
-
#initialize(options) ⇒ Pool
constructor
Initialize a new connection pool with the given options.
Constructor Details
#initialize(options) ⇒ Pool
Initialize a new connection pool with the given options.
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/oedipus/connection/pool.rb', line 32 def initialize() @host = [:host] @port = [:port] @size = .fetch(:size, 8) @ttl = .fetch(:ttl, 60) @available = [] @used = {} @expiries = {} @condition = ConditionVariable.new @lock = Mutex.new sweeper end |
Instance Method Details
#acquire ⇒ Object
Acquire a connection from the pool, for the duration of a block.
The release of the connection is done automatically.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/oedipus/connection/pool.rb', line 54 def acquire instance = nil begin @lock.synchronize do if instance = @available.pop @used[instance] = instance elsif @size > (@available.size + @used.size) instance = new_instance else @condition.wait(@lock) end end end until instance yield instance ensure release(instance) end |
#dispose ⇒ Object
Dispose all connections in the pool.
Waits until all connections have finished processing current queries and then releases them.
77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/oedipus/connection/pool.rb', line 77 def dispose begin @lock.synchronize do while instance = @available.pop instance.close end @condition.wait(@lock) if @used.size > 0 end end until empty? end |
#empty? ⇒ Boolean
Returns true if the pool is currently empty.
93 94 95 |
# File 'lib/oedipus/connection/pool.rb', line 93 def empty? @lock.synchronize { @used.size == 0 && @available.size == 0 } end |