class SimplePool(T)

Overview

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

Defined in:

simplepool.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new(size : Int32, factory : -> T) #

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


[View source]
def self.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


[View source]
def self.new(size : Int32 = 1) #

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


[View source]

Instance Method Detail

def get : T #

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


[View source]
def 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


[View source]
def use(& : T -> U) : U forall U #

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


[View source]