Class: QuackPool
- Inherits:
-
Object
- Object
- QuackPool
- Defined in:
- lib/quack_pool.rb,
lib/quack_pool/error.rb
Defined Under Namespace
Classes: Error
Instance Method Summary collapse
- #absorb_resource(resource) ⇒ Object
- #has_resource?(resource) ⇒ Boolean
-
#initialize(resource_class:, size: Float::INFINITY) ⇒ QuackPool
constructor
A new instance of QuackPool.
- #release_resource ⇒ Object
- #resource_available?(resource) ⇒ Boolean
Constructor Details
#initialize(resource_class:, size: Float::INFINITY) ⇒ QuackPool
Returns a new instance of QuackPool.
8 9 10 11 12 13 14 15 16 17 |
# File 'lib/quack_pool.rb', line 8 def initialize(resource_class: , size: Float::INFINITY) raise ArgumentError, "'resource_class' must respond_to 'new'" unless resource_class.respond_to?(:new) @resource_class = resource_class raise ArgumentError, "'size' must be an Integer" unless size.is_a?(Integer) || size == Float::INFINITY @max_size = size @resources = [] @available_resources = [] @mutex = ReentrantMutex.new @condition_variable = ConditionVariable.new end |
Instance Method Details
#absorb_resource(resource) ⇒ Object
19 20 21 22 23 24 25 26 27 |
# File 'lib/quack_pool.rb', line 19 def absorb_resource(resource) @mutex.synchronize do raise Error, "resource does not belong to this pool" unless has_resource?(resource) raise Error, "resource already in pool" if resource_available?(resource) @available_resources.push(resource) @condition_variable.signal end nil end |
#has_resource?(resource) ⇒ Boolean
29 30 31 32 33 34 |
# File 'lib/quack_pool.rb', line 29 def has_resource?(resource) @mutex.synchronize do raise Error, "resource is not an instance of 'resource_class'" unless resource.is_a?(@resource_class) @resources.include?(resource) end end |
#release_resource ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/quack_pool.rb', line 36 def release_resource @mutex.synchronize do if @available_resources.any? release_available_resource elsif @resources.length < @max_size build_new_resource else release_next_available_resource end end end |
#resource_available?(resource) ⇒ Boolean
48 49 50 51 52 53 |
# File 'lib/quack_pool.rb', line 48 def resource_available?(resource) @mutex.synchronize do raise Error, "resource does not belong to this pool" unless has_resource?(resource) @available_resources.include?(resource) end end |