Class: Concurrent::BlockingRingBuffer

Inherits:
Object
  • Object
show all
Defined in:
lib/concurrent/collection/blocking_ring_buffer.rb

Instance Method Summary collapse

Constructor Details

#initialize(capacity) ⇒ BlockingRingBuffer

Returns a new instance of BlockingRingBuffer.



6
7
8
9
10
11
12
# File 'lib/concurrent/collection/blocking_ring_buffer.rb', line 6

def initialize(capacity)
  @buffer = RingBuffer.new(capacity)
  @first = @last = 0
  @count = 0
  @mutex = Mutex.new
  @condition = Condition.new
end

Instance Method Details

#capacityInteger

Returns the capacity of the buffer.

Returns:

  • (Integer)

    the capacity of the buffer



15
16
17
# File 'lib/concurrent/collection/blocking_ring_buffer.rb', line 15

def capacity
  @mutex.synchronize { @buffer.capacity }
end

#countInteger

Returns the number of elements currently in the buffer.

Returns:

  • (Integer)

    the number of elements currently in the buffer



20
21
22
# File 'lib/concurrent/collection/blocking_ring_buffer.rb', line 20

def count
  @mutex.synchronize { @buffer.count }
end

#empty?Boolean

Returns true if buffer is empty, false otherwise.

Returns:

  • (Boolean)

    true if buffer is empty, false otherwise



25
26
27
# File 'lib/concurrent/collection/blocking_ring_buffer.rb', line 25

def empty?
  @mutex.synchronize { @buffer.empty? }
end

#full?Boolean

Returns true if buffer is full, false otherwise.

Returns:

  • (Boolean)

    true if buffer is full, false otherwise



30
31
32
# File 'lib/concurrent/collection/blocking_ring_buffer.rb', line 30

def full?
  @mutex.synchronize { @buffer.full? }
end

#peekObject

Returns the first available value and without removing it from the buffer. If buffer is empty returns nil.

Returns:

  • (Object)

    the first available value and without removing it from the buffer. If buffer is empty returns nil



56
57
58
# File 'lib/concurrent/collection/blocking_ring_buffer.rb', line 56

def peek
  @mutex.synchronize { @buffer.peek }
end

#put(value) ⇒ Boolean

Returns true if value has been inserted, false otherwise.

Parameters:

  • value (Object)

    the value to be inserted

Returns:

  • (Boolean)

    true if value has been inserted, false otherwise



36
37
38
39
40
41
42
43
# File 'lib/concurrent/collection/blocking_ring_buffer.rb', line 36

def put(value)
  @mutex.synchronize do
    wait_while_full
    @buffer.offer(value)
    @condition.signal
    true
  end
end

#takeObject

Returns the first available value and removes it from the buffer. If buffer is empty it blocks until an element is available.

Returns:

  • (Object)

    the first available value and removes it from the buffer. If buffer is empty it blocks until an element is available



46
47
48
49
50
51
52
53
# File 'lib/concurrent/collection/blocking_ring_buffer.rb', line 46

def take
  @mutex.synchronize do
    wait_while_empty
    result = @buffer.poll
    @condition.signal
    result
  end
end