Class: Pool

Inherits:
Array show all
Includes:
MonitorMixin
Defined in:
lib/more/facets/pool.rb

Overview

Pool

Generalized object pool implementation. Implemented as a thread safe stack. Exclusive locking is needed both for push and pop.

Instance Method Summary collapse

Methods inherited from Array

#at_rand, #at_rand!, cast_from, #conjoin, #delete_unless, #delete_values, #delete_values_at, #each_iteration, #merge!, mutable_methods, #not_empty?, #only, #pad, #pad!, #pick, #pick!, #rand_index, #rand_subset, #restore_snapshot, #rotate, #rotate!, #select!, #shuffle, #shuffle!, #splice, #take_snapshot, #to_b, #to_console, #to_h, #to_path, #to_t

Methods included from Stackable

#peek, #poke, #pull

Methods included from Indexable

#body, #ends, #first, #first!, #first=, #foot, #head, #index_of, #last, #last!, #last=, #mid, #middle, #pos, #range, #tail, #thru

Constructor Details

#initializePool

Returns a new instance of Pool.



45
46
47
48
# File 'lib/more/facets/pool.rb', line 45

def initialize
  super
  @cv = new_cond()
end

Instance Method Details

#obtainObject

Obtains an object, passes it to a block for processing and restores it to the pool.



71
72
73
74
75
76
77
78
79
80
# File 'lib/more/facets/pool.rb', line 71

def obtain
  result = nil
  begin
    obj = pop()
    result = yield(obj)
  ensure
    push(obj)
  end
  return result
end

#popObject

Obtain an object from the pool.



61
62
63
64
65
66
# File 'lib/more/facets/pool.rb', line 61

def pop
  synchronize do
    @cv.wait_while { empty? }
    super
  end
end

#push(obj) ⇒ Object

Add, restore an object to the pool.



52
53
54
55
56
57
# File 'lib/more/facets/pool.rb', line 52

def push(obj)
  synchronize do
    super
    @cv.signal()
  end
end