Parent

Files

Class Index [+]

Quicksearch

ActiveRecord::ConnectionAdapters::ConnectionPool

Connection pool base class for managing Active Record database connections.

Introduction

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.

Obtaining (checking out) a connection

Connections can be obtained and used from a connection pool in several ways:

  1. 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.

  2. 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).

  3. 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).

Options

There are two connection-pooling-related options that you can add to your database connection configuration:

Attributes

spec[R]
connections[R]

Public Class Methods

new(spec) click to toggle source

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 = spec.config[:wait_timeout] || 5
79: 
80:         # default max pool size to 5
81:         @size = (spec.config[:pool] && spec.config[:pool].to_i) || 5
82: 
83:         @connections = []
84:         @checked_out = []
85:       end

Public Instance Methods

checkin(conn) click to toggle source

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 214
214:       def checkin(conn)
215:         @connection_mutex.synchronize do
216:           conn.send(:_run_checkin_callbacks) do
217:             @checked_out.delete conn
218:             @queue.signal
219:           end
220:         end
221:       end
checkout() click to toggle source

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 183
183:       def checkout
184:         # Checkout an available connection
185:         @connection_mutex.synchronize do
186:           loop do
187:             conn = if @checked_out.size < @connections.size
188:                      checkout_existing_connection
189:                    elsif @connections.size < @size
190:                      checkout_new_connection
191:                    end
192:             return conn if conn
193: 
194:             @queue.wait(@timeout)
195: 
196:             if(@checked_out.size < @connections.size)
197:               next
198:             else
199:               clear_stale_cached_connections!
200:               if @size == @checked_out.size
201:                 raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout}.  The max pool size is currently #{@size}; consider increasing it."
202:               end
203:             end
204: 
205:           end
206:         end
207:       end
clear_reloadable_connections!() click to toggle source

Clears the cache which maps classes

     # File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 133
133:       def clear_reloadable_connections!
134:         @reserved_connections.each do |name, conn|
135:           checkin conn
136:         end
137:         @reserved_connections = {}
138:         @connections.each do |conn|
139:           conn.disconnect! if conn.requires_reloading?
140:         end
141:         @connections.delete_if do |conn|
142:           conn.requires_reloading?
143:         end
144:       end
clear_stale_cached_connections!() click to toggle source

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 157
157:       def clear_stale_cached_connections!
158:         keys = @reserved_connections.keys - Thread.list.find_all { |t|
159:           t.alive?
160:         }.map { |thread| thread.object_id }
161:         keys.each do |key|
162:           checkin @reserved_connections[key]
163:           @reserved_connections.delete(key)
164:         end
165:       end
connected?() click to toggle source

Returns true if a connection has already been opened.

     # File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 116
116:       def connected?
117:         !@connections.empty?
118:       end
connection() click to toggle source

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 92
92:       def connection
93:         @reserved_connections[current_connection_id] ||= checkout
94:       end
disconnect!() click to toggle source

Disconnects all connections in the pool, and clears the pool.

     # File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 121
121:       def disconnect!
122:         @reserved_connections.each do |name,conn|
123:           checkin conn
124:         end
125:         @reserved_connections = {}
126:         @connections.each do |conn|
127:           conn.disconnect!
128:         end
129:         @connections = []
130:       end
release_connection(with_id = current_connection_id) click to toggle source

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 99
 99:       def release_connection(with_id = current_connection_id)
100:         conn = @reserved_connections.delete(with_id)
101:         checkin conn if conn
102:       end
with_connection() click to toggle source

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 107
107:       def with_connection
108:         connection_id = current_connection_id
109:         fresh_connection = true unless @reserved_connections[connection_id]
110:         yield connection
111:       ensure
112:         release_connection(connection_id) if fresh_connection
113:       end

Private Instance Methods

checkout_and_verify(c) click to toggle source
     # File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 246
246:       def checkout_and_verify(c)
247:         c.run_callbacks :checkout do
248:           c.verify!
249:           @checked_out << c
250:         end
251:         c
252:       end
checkout_existing_connection() click to toggle source
     # File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 241
241:       def checkout_existing_connection
242:         c = (@connections - @checked_out).first
243:         checkout_and_verify(c)
244:       end
checkout_new_connection() click to toggle source
     # File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 235
235:       def checkout_new_connection
236:         c = new_connection
237:         @connections << c
238:         checkout_and_verify(c)
239:       end
new_connection() click to toggle source
     # File lib/active_record/connection_adapters/abstract/connection_pool.rb, line 227
227:       def new_connection
228:         ActiveRecord::Base.send(spec.adapter_method, spec.config)
229:       end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.