class Bundler::ConnectionPool
- :timeout - amount of time to wait for a connection if none currently available, defaults to 5 seconds
- :size - number of connections to pool, defaults to 5
Accepts the following options:
end
$redis.lpop(‘my-list’) if $redis.llen(‘my-list’) > 0
def do_work
$redis = Bundler::ConnectionPool.wrap { Redis.new }
Example usage replacing an existing connection (slower):
end
redis.lpop(‘my-list’) if redis.llen(‘my-list’) > 0
@pool.with(timeout: 2.0) do |redis|
Using optional timeout override (for that single invocation)
end
redis.lpop(‘my-list’) if redis.llen(‘my-list’) > 0
@pool.with do |redis|
@pool = Bundler::ConnectionPool.new { Redis.new }
Example usage with block (faster):
among many threads. Note: Connections are lazily created.
Generic connection pool class for e.g. sharing a limited number of network connections
def self.wrap(options, &block)
def self.wrap(options, &block) Wrapper.new(options, &block) end
def available
def available @available.length end
def checkin
def checkin if ::Thread.current[@key] if ::Thread.current[@key_count] == 1 @available.push(::Thread.current[@key]) ::Thread.current[@key]= nil else ::Thread.current[@key_count]-= 1 end else raise Bundler::ConnectionPool::Error, 'no connections are checked out' end nil end
def checkout(options = {})
def checkout(options = {}) if ::Thread.current[@key] ::Thread.current[@key_count]+= 1 ::Thread.current[@key] else ::Thread.current[@key_count]= 1 ::Thread.current[@key]= @available.pop(options[:timeout] || @timeout) end end
def get_time
def get_time Process.clock_gettime(Process::CLOCK_MONOTONIC) end
def get_time
def get_time java.lang.System.nanoTime() / 1_000_000_000.0 end
def get_time
def get_time @mutex.synchronize do now = Time.now.to_f if @last_time < now @last_time = now else # clock has moved back in time @last_time += 0.000_001 end end end
def initialize(options = {}, &block)
def initialize(options = {}, &block) raise ArgumentError, 'Connection pool requires a block' unless block options = DEFAULTS.merge(options) @size = options.fetch(:size) @timeout = options.fetch(:timeout) @available = TimedStack.new(@size, &block) @key = :"current-#{@available.object_id}" @key_count = :"current-#{@available.object_id}-count" end
def initialize
def initialize @mutex = Mutex.new @last_time = Time.now.to_f end
def monotonic_time
-
(Float)
- The current monotonic time when `since` not given else
def monotonic_time GLOBAL_MONOTONIC_CLOCK.get_time end
def shutdown(&block)
def shutdown(&block) @available.shutdown(&block) end
def size
def size @size end
def with(options = {})
def with(options = {}) Thread.handle_interrupt(Exception => :never) do conn = checkout(options) begin Thread.handle_interrupt(Exception => :immediate) do yield conn end ensure checkin end end end
def with(options = {})
def with(options = {}) conn = checkout(options) begin yield conn ensure checkin end end