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


41
42
43
44
45
46
47
48
49
50
# File 'lib/never_block/pool/fibered_connection_pool.rb', line 41

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.



32
33
34
# File 'lib/never_block/pool/fibered_connection_pool.rb', line 32

def size
  @size
end

Instance Method Details

#all_connectionsObject



67
68
69
# File 'lib/never_block/pool/fibered_connection_pool.rb', line 67

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

#hold {|conn| ... } ⇒ Object

If a connection is available, pass it to the block, otherwise pass the fiber to the queue till a connection is available

Yields:

  • (conn)


61
62
63
64
65
# File 'lib/never_block/pool/fibered_connection_pool.rb', line 61

def hold()
  fiber = Fiber.current
     conn = acquire(fiber)
     yield conn
end

#replace_acquired_connectionObject



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

def replace_acquired_connection
  fiber = Fiber.current
  conn = @connection_proc.call
  @busy_connections[fiber] = conn
  fiber[connection_pool_key] = conn
end