Class: ResourcePool
- Inherits:
-
Object
- Object
- ResourcePool
- Defined in:
- lib/resource_pool.rb
Defined Under Namespace
Classes: InvalidCreateProc, ResourceNotAvailable, 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
-
#trash_current! ⇒ Object
please only call this inside hold block.
Constructor Details
#initialize(opts = {}, &block) ⇒ ResourcePool
Returns a new instance of ResourcePool.
8 9 10 11 12 13 14 15 16 17 |
# File 'lib/resource_pool.rb', line 8 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.
6 7 8 |
# File 'lib/resource_pool.rb', line 6 def allocated @allocated end |
#max_size ⇒ Object (readonly)
Returns the value of attribute max_size.
6 7 8 |
# File 'lib/resource_pool.rb', line 6 def max_size @max_size end |
#pool ⇒ Object (readonly)
Returns the value of attribute pool.
6 7 8 |
# File 'lib/resource_pool.rb', line 6 def pool @pool end |
Instance Method Details
#hold ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/resource_pool.rb', line 31 def hold t = Thread.current if res = owned_resource(t) return yield(res) end begin unless res = acquire(t) raise ResourceNotAvailable if @timeout == 0 time = Time.now timeout = time + @timeout sleep_time = @sleep_time sleep sleep_time until res = acquire(t) raise ResourceNotAvailable if Time.now > timeout sleep sleep_time end end yield res ensure sync{release(t)} if owned_resource(t) end end |
#release_all(&block) ⇒ Object
23 24 25 26 27 28 29 |
# File 'lib/resource_pool.rb', line 23 def release_all(&block) block ||= @delete_proc sync do @pool.each{|res| block.call(res)} if block @pool.clear end end |
#size ⇒ Object
19 20 21 |
# File 'lib/resource_pool.rb', line 19 def size @allocated.length + @pool.length end |
#trash_current! ⇒ Object
please only call this inside hold block
56 57 58 59 60 61 62 63 64 |
# File 'lib/resource_pool.rb', line 56 def trash_current! t = Thread.current conn = owned_resource(t) return unless conn @delete_proc.call conn if @delete_proc sync { @allocated.delete(t) } nil end |