Class: ActiveRecord::Bogacs::DefaultPool::Queue

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/bogacs/default_pool.rb

Overview

Threadsafe, fair, FIFO queue. Meant to be used by ConnectionPool with which it shares a Monitor. But could be a generic Queue.

The Queue in stdlib’s ‘thread’ could replace this class except stdlib’s doesn’t support waiting with a timeout.

Instance Method Summary collapse

Constructor Details

#initialize(lock) ⇒ Queue



28
29
30
31
32
33
# File 'lib/active_record/bogacs/default_pool.rb', line 28

def initialize(lock)
  @lock = lock
  @cond = @lock.new_cond
  @num_waiting = 0
  @queue = []
end

Instance Method Details

#add(element) ⇒ Object

Add element to the queue. Never blocks.



51
52
53
54
55
56
# File 'lib/active_record/bogacs/default_pool.rb', line 51

def add(element)
  synchronize do
    @queue.push element
    @cond.signal
  end
end

#any_waiting?Boolean

Test if any threads are currently waiting on the queue.



36
37
38
39
40
# File 'lib/active_record/bogacs/default_pool.rb', line 36

def any_waiting?
  synchronize do
    @num_waiting > 0
  end
end

#clearObject

Remove all elements from the queue.



66
67
68
69
70
# File 'lib/active_record/bogacs/default_pool.rb', line 66

def clear
  synchronize do
    @queue.clear
  end
end

#delete(element) ⇒ Object

If element is in the queue, remove and return it, or nil.



59
60
61
62
63
# File 'lib/active_record/bogacs/default_pool.rb', line 59

def delete(element)
  synchronize do
    @queue.delete(element)
  end
end

#num_waitingObject

Returns the number of threads currently waiting on this queue.



44
45
46
47
48
# File 'lib/active_record/bogacs/default_pool.rb', line 44

def num_waiting
  synchronize do
    @num_waiting
  end
end

#poll(timeout = nil, &block) ⇒ Object

Remove the head of the queue.

If timeout is not given, remove and return the head the queue if the number of available elements is strictly greater than the number of threads currently waiting (that is, don’t jump ahead in line). Otherwise, return nil.

If timeout is given, block if it there is no element available, waiting up to timeout seconds for an element to become available.

becomes available after timeout seconds

Raises:

  • (ActiveRecord::ConnectionTimeoutError)

    if timeout given and no element



85
86
87
88
89
90
91
92
93
# File 'lib/active_record/bogacs/default_pool.rb', line 85

def poll(timeout = nil, &block)
  synchronize do
    if timeout
      no_wait_poll || wait_poll(timeout, &block)
    else
      no_wait_poll
    end
  end
end