Object
Connection pool base class for managing Active Record database connections.
A connection pool synchronizes thread access to a limited number of database connections. The basic idea is that each thread checks out a database connection from the pool, uses that connection, and checks the connection back in. ConnectionPool is completely thread-safe, and will ensure that a connection cannot be used by two threads at the same time, as long as ConnectionPool’s contract is correctly followed. It will also handle cases in which there are more threads than connections: if all connections have been checked out, and a thread tries to checkout a connection anyway, then ConnectionPool will wait until some other thread has checked in a connection.
Connections can be obtained and used from a connection pool in several ways:
Simply use ActiveRecord::Base.connection as with Active Record 2.1 and earlier (pre-connection-pooling). Eventually, when you’re done with the connection(s) and wish it to be returned to the pool, you call ActiveRecord::Base.clear_active_connections!. This will be the default behavior for Active Record when used in conjunction with Action Pack’s request handling cycle.
Manually check out a connection from the pool with ActiveRecord::Base.connection_pool.checkout. You are responsible for returning this connection to the pool when finished by calling ActiveRecord::Base.connection_pool.checkin(connection).
Use ActiveRecord::Base.connection_pool.with_connection(&block), which obtains a connection, yields it as the sole argument to the block, and returns it to the pool after the block completes.
Connections in the pool are actually AbstractAdapter objects (or objects compatible with AbstractAdapter’s interface).
There are two connection-pooling-related options that you can add to your database connection configuration:
pool: number indicating size of connection pool (default 5)
wait_timeout: number of seconds to block and wait for a connection before giving up and raising a timeout error (default 5 seconds).
Creates a new ConnectionPool object. spec is a ConnectionSpecification object which describes database connection information (e.g. adapter, host name, username, password, etc), as well as the maximum size for this ConnectionPool.
The default ConnectionPool maximum size is 5.
# File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 67 67: def initialize(spec) 68: @spec = spec 69: 70: # The cache of reserved connections mapped to threads 71: @reserved_connections = {} 72: 73: # The mutex used to synchronize pool access 74: @connection_mutex = Monitor.new 75: @queue = @connection_mutex.new_cond 76: 77: # default 5 second timeout unless on ruby 1.9 78: @timeout = 79: if RUBY_VERSION < '1.9' 80: spec.config[:wait_timeout] || 5 81: end 82: 83: # default max pool size to 5 84: @size = (spec.config[:pool] && spec.config[:pool].to_i) || 5 85: 86: @connections = [] 87: @checked_out = [] 88: end
Check-in a database connection back into the pool, indicating that you no longer need this connection.
conn: an AbstractAdapter object, which was obtained by earlier by calling checkout on this pool.
# File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 216 216: def checkin(conn) 217: @connection_mutex.synchronize do 218: conn.send(:_run_checkin_callbacks) do 219: @checked_out.delete conn 220: @queue.signal 221: end 222: end 223: end
Check-out a database connection from the pool, indicating that you want to use it. You should call # when you no longer need this.
This is done by either returning an existing connection, or by creating a new connection. If the maximum number of connections for this pool has already been reached, but the pool is empty (i.e. they’re all being used), then this method will wait until a thread has checked in a connection. The wait time is bounded however: if no connection can be checked out within the timeout specified for this pool, then a ConnectionTimeoutError exception will be raised.
Returns: an AbstractAdapter object.
Raises:
ConnectionTimeoutError: no connection can be obtained from the pool within the timeout period.
# File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 187 187: def checkout 188: # Checkout an available connection 189: @connection_mutex.synchronize do 190: loop do 191: conn = if @checked_out.size < @connections.size 192: checkout_existing_connection 193: elsif @connections.size < @size 194: checkout_new_connection 195: end 196: return conn if conn 197: # No connections available; wait for one 198: if @queue.wait(@timeout) 199: next 200: else 201: # try looting dead threads 202: clear_stale_cached_connections! 203: if @size == @checked_out.size 204: raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout}. The max pool size is currently #{@size}; consider increasing it." 205: end 206: end 207: end 208: end 209: end
Clears the cache which maps classes
# File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 136 136: def clear_reloadable_connections! 137: @reserved_connections.each do |name, conn| 138: checkin conn 139: end 140: @reserved_connections = {} 141: @connections.each do |conn| 142: conn.disconnect! if conn.requires_reloading? 143: end 144: @connections.delete_if do |conn| 145: conn.requires_reloading? 146: end 147: end
Return any checked-out connections back to the pool by threads that are no longer alive.
# File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 160 160: def clear_stale_cached_connections! 161: keys = @reserved_connections.keys - Thread.list.find_all { |t| 162: t.alive? 163: }.map { |thread| thread.object_id } 164: 165: keys.each do |key| 166: checkin @reserved_connections[key] 167: @reserved_connections.delete(key) 168: end 169: end
Returns true if a connection has already been opened.
# File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 119 119: def connected? 120: !@connections.empty? 121: end
Retrieve the connection associated with the current thread, or call # to obtain one if necessary.
# can be called any number of times; the connection is held in a hash keyed by the thread id.
# File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 95 95: def connection 96: @reserved_connections[current_connection_id] ||= checkout 97: end
Disconnects all connections in the pool, and clears the pool.
# File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 124 124: def disconnect! 125: @reserved_connections.each do |name,conn| 126: checkin conn 127: end 128: @reserved_connections = {} 129: @connections.each do |conn| 130: conn.disconnect! 131: end 132: @connections = [] 133: end
Signal that the thread is finished with the current connection. # releases the connection-thread association and returns the connection to the pool.
# File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 102 102: def release_connection(with_id = current_connection_id) 103: conn = @reserved_connections.delete(with_id) 104: checkin conn if conn 105: end
If a connection already exists yield it to the block. If no connection exists checkout a connection, yield it to the block, and checkin the connection when finished.
# File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 110 110: def with_connection 111: connection_id = current_connection_id 112: fresh_connection = true unless @reserved_connections[connection_id] 113: yield connection 114: ensure 115: release_connection(connection_id) if fresh_connection 116: end
# File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 248 248: def checkout_and_verify(c) 249: c.run_callbacks :checkout do 250: c.verify! 251: @checked_out << c 252: end 253: c 254: end
# File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 243 243: def checkout_existing_connection 244: c = (@connections - @checked_out).first 245: checkout_and_verify(c) 246: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.