class

SimplePool(T)

Inherits Reference < Object

Simple thread safe pool for anything

Example of usage:

# Note that `MyConnection.new` will be protected by mutex, so can be not thread-safe
pool = SimplePool(MyConnection).new { MyConnection.new(address, port) }
10.times do
  spawn do
    # get object from pool
    conn = pool.get
    work_with(conn)
    # don't forget to return it
    pool.return(conn)
  end
end
10.times do
  spawn do
    # safe version as you don't need to explicitely return it
    pool.use do |conn|
      work_with conn
      raise "error" # object will be returned to pool even after raise
    end
  end
end

Constructors

new(size : Int32, factory : -> T)

Creates a pool of type T, with initial capacity size. New instances of T are constructed using factory call

Source
new(size : Int32 = 1, &block : -> T)

Creates a pool of type T, with initial capacity size. New instances of T are constructed using inline block

Source
new(size : Int32 = 1)

Creates a pool of type T, with initial capacity size. New instances of T are constructed using T.new

Source

Instance methods

get

Returns object from a pool. Object should be returned to the pool later, otherwise it will be garbage collected.

Source
return(object : T)

Returns object to the pool.

Actually, you can even "return" objects that wasn't in pool initially, so use it as alternative form of filling pool

Source
use

Yield a block with object from a pool. Object will be automatatically returned to the pool after block completion

Source