Class: NeverBlock::Pool::FiberedConnectionPool

Inherits:
Object
  • Object
show all
Defined in:
lib/never_block/pool/fibered_connection_pool.rb

Overview

Example:

pool = NeverBlock::Pool::FiberedConnectionPool.new(:size=>16)do

# connection creation code goes here

end 32.times do

Fiber.new do
  # acquire a connection from the pool
  pool.hold do |conn|
    conn.execute('something') # you can use the connection normally now
  end
end.resume

end

The pool has support for transactions, just pass true to the pool#hold method and the connection will not be released after the block is finished It is the responsibility of client code to release the connection

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, &block) ⇒ FiberedConnectionPool

initialize the connection pool using the supplied proc to create the connections You can choose to start them eagerly or lazily (lazy by default) Available options are

:size => the maximum number of connections to be created in the pool
:eager => (true|false) indicates whether connections should be
          created initially or when need


50
51
52
53
54
55
56
57
58
59
# File 'lib/never_block/pool/fibered_connection_pool.rb', line 50

def initialize(options = {}, &block)
  @connections, @busy_connections, @queue = [], {},[]
  @connection_proc = block
  @size = options[:size] || 8
  if options[:eager]
    @size.times do
      @connections << @connection_proc.call
    end
  end
end

Instance Attribute Details

#sizeObject (readonly)

Returns the value of attribute size.



41
42
43
# File 'lib/never_block/pool/fibered_connection_pool.rb', line 41

def size
  @size
end

Instance Method Details

#all_connectionsObject



88
89
90
# File 'lib/never_block/pool/fibered_connection_pool.rb', line 88

def all_connections
  (@connections + @busy_connections.values).each {|conn| yield(conn)}
end

#hold(transactional = false) ⇒ Object

If a connection is available, pass it to the block, otherwise pass the fiber to the queue till a connection is available when done with a connection try to porcess other fibers in the queue before releasing the connection if inside a transaction, don’t release the fiber



66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/never_block/pool/fibered_connection_pool.rb', line 66

def hold(transactional = false)
  fiber = Fiber.current
  if conn = @busy_connections[fiber]
    return yield(conn)
  end
  conn = acquire(fiber)
  begin
    yield conn
  ensure
    release(fiber, conn) unless transactional
    process_queue
  end
end

#release(fiber, conn) ⇒ Object

Give the fiber back to the pool you have to call this explicitly if you held a connection for a transaction



83
84
85
86
# File 'lib/never_block/pool/fibered_connection_pool.rb', line 83

def release(fiber, conn)
  @busy_connections.delete(fiber)
  @connections << conn
end