Class: ResourcePool
- Inherits:
-
Object
- Object
- ResourcePool
- Defined in:
- lib/resource_pool.rb
Defined Under Namespace
Classes: BadResource, InvalidCreateProc, PoolTimeout, ResourcePoolError
Instance Attribute Summary collapse
-
#allocated ⇒ Object
readonly
Returns the value of attribute allocated.
-
#max_size ⇒ Object
readonly
Returns the value of attribute max_size.
-
#pool ⇒ Object
readonly
Returns the value of attribute pool.
Instance Method Summary collapse
- #hold ⇒ Object
-
#initialize(opts = {}, &block) ⇒ ResourcePool
constructor
A new instance of ResourcePool.
- #release_all(&block) ⇒ Object
- #size ⇒ Object
Constructor Details
#initialize(opts = {}, &block) ⇒ ResourcePool
Returns a new instance of ResourcePool.
9 10 11 12 13 14 15 16 17 18 |
# File 'lib/resource_pool.rb', line 9 def initialize(opts={}, &block) @max_size = opts[:max_size] || 4 @create_proc = block @pool = [] @allocated = {} @mutex = Mutex.new @timeout = opts[:pool_timeout] || 2 @sleep_time = opts[:pool_sleep_time] || 0.001 @delete_proc = opts[:delete_proc] end |
Instance Attribute Details
#allocated ⇒ Object (readonly)
Returns the value of attribute allocated.
7 8 9 |
# File 'lib/resource_pool.rb', line 7 def allocated @allocated end |
#max_size ⇒ Object (readonly)
Returns the value of attribute max_size.
7 8 9 |
# File 'lib/resource_pool.rb', line 7 def max_size @max_size end |
#pool ⇒ Object (readonly)
Returns the value of attribute pool.
7 8 9 |
# File 'lib/resource_pool.rb', line 7 def pool @pool end |
Instance Method Details
#hold ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/resource_pool.rb', line 32 def hold t = Thread.current if res = owned_resource(t) return yield(res) end begin unless res = acquire(t) time = Time.now timeout = time + @timeout sleep_time = @sleep_time sleep sleep_time until res = acquire(t) raise PoolTimeout if Time.now > timeout sleep sleep_time end end yield res rescue BadResource old_res = res res = nil @delete_proc.call(res) if @delete_proc && old_res @allocated.delete(t) raise ensure sync{release(t)} if res end end |
#release_all(&block) ⇒ Object
24 25 26 27 28 29 30 |
# File 'lib/resource_pool.rb', line 24 def release_all(&block) block ||= @delete_proc sync do @pool.each{|res| block.call(res)} if block @pool.clear end end |
#size ⇒ Object
20 21 22 |
# File 'lib/resource_pool.rb', line 20 def size @allocated.length + @pool.length end |