| Class | ConnectionPool |
| In: |
lib/assistance/connection_pool.rb
|
| Parent: | Object |
A ConnectionPool manages access to database connections by keeping multiple connections and giving threads exclusive access to each connection.
| allocated | [R] | |
| available_connections | [R] | |
| connection_proc | [RW] | The proc used to create a new connection. |
| created_count | [R] | |
| max_size | [R] | The maximum number of connections. |
| mutex | [R] |
Constructs a new pool with a maximum size. If a block is supplied, it is used to create new connections as they are needed.
pool = ConnectionPool.new(10) {MyConnection.new(opts)}
The connection creation proc can be changed at any time by assigning a Proc to pool#connection_proc.
pool = ConnectionPool.new(10)
pool.connection_proc = proc {MyConnection.new(opts)}
# File lib/assistance/connection_pool.rb, line 27
27: def initialize(max_size = 4, &block)
28: @max_size = max_size
29: @mutex = Mutex.new
30: @connection_proc = block
31:
32: @available_connections = []
33: @allocated = {}
34: @created_count = 0
35: end
Removes all connection currently available, optionally yielding each connection to the given block. This method has the effect of disconnecting from the database. Once a connection is requested using hold, the connection pool creates new connections to the database.
# File lib/assistance/connection_pool.rb, line 74
74: def disconnect(&block)
75: @mutex.synchronize do
76: @available_connections.each {|c| block[c]} if block
77: @available_connections = []
78: @created_count = @allocated.size
79: end
80: end
Assigns a connection to the current thread, yielding the connection to the supplied block.
pool.hold {|conn| conn.execute('DROP TABLE posts')}
Pool#hold is re-entrant, meaning it can be called recursively in the same thread without blocking.
If no connection is available, Pool#hold will block until a connection is available.
# File lib/assistance/connection_pool.rb, line 52
52: def hold
53: t = Thread.current
54: if (conn = owned_connection(t))
55: return yield(conn)
56: end
57: while !(conn = acquire(t))
58: sleep 0.001
59: end
60: begin
61: yield conn
62: ensure
63: release(t)
64: end
65: rescue Exception => e
66: # if the error is not a StandardError it is converted into RuntimeError.
67: raise e.is_a?(StandardError) ? e : e.message
68: end