class Bundler::ConnectionPool
def self.after_fork
def self.after_fork INSTANCES.values.each do |pool| next unless pool.auto_reload_after_fork # We're on after fork, so we know all other threads are dead. # All we need to do is to ensure the main thread doesn't have a # checked out connection pool.checkin(force: true) pool.reload do |connection| # Unfortunately we don't know what method to call to close the connection, # so we try the most common one. connection.close if connection.respond_to?(:close) end end nil end
def self.after_fork
def self.after_fork # noop end
def self.wrap(options, &block)
def self.wrap(options, &block) Wrapper.new(options, &block) end
def available
def available @available.length end
def checkin(force: false)
def checkin(force: false) if ::Thread.current[@key] if ::Thread.current[@key_count] == 1 || force @available.push(::Thread.current[@key]) ::Thread.current[@key] = nil ::Thread.current[@key_count] = nil else ::Thread.current[@key_count] -= 1 end elsif !force 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 initialize(options = {}, &block)
def initialize(options = {}, &block) raise ArgumentError, "Connection pool requires a block" unless block options = DEFAULTS.merge(options) @size = Integer(options.fetch(:size)) @timeout = options.fetch(:timeout) @auto_reload_after_fork = options.fetch(:auto_reload_after_fork) @available = TimedStack.new(@size, &block) @key = :"pool-#{@available.object_id}" @key_count = :"pool-#{@available.object_id}-count" INSTANCES[self] = self if INSTANCES end
def reload(&block)
def reload(&block) @available.shutdown(reload: true, &block) end
def shutdown(&block)
def shutdown(&block) @available.shutdown(&block) 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