Class: Datadog::Core::Buffer::Random

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog/core/buffer/random.rb

Overview

Buffer that stores objects. The buffer has a maximum size and when the buffer is full, a random object is discarded.

Direct Known Subclasses

CRuby, ThreadSafe

Instance Method Summary collapse

Constructor Details

#initialize(max_size) ⇒ Random

Returns a new instance of Random.



12
13
14
15
16
# File 'lib/datadog/core/buffer/random.rb', line 12

def initialize(max_size)
  @max_size = max_size
  @items = []
  @closed = false
end

Instance Method Details

#closeObject

Closes this buffer, preventing further pushing. Draining is still allowed.



63
64
65
# File 'lib/datadog/core/buffer/random.rb', line 63

def close
  @closed = true
end

#closed?Boolean

Returns:

  • (Boolean)


67
68
69
# File 'lib/datadog/core/buffer/random.rb', line 67

def closed?
  @closed
end

#concat(items) ⇒ Object

A bulk push alternative to #push. Use this method if pushing more than one item for efficiency.



33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/datadog/core/buffer/random.rb', line 33

def concat(items)
  return if closed?

  # Segment items into underflow and overflow
  underflow, overflow = overflow_segments(items)

  # Concatenate items do not exceed capacity.
  add_all!(underflow) unless underflow.nil?

  # Iteratively replace items, to ensure pseudo-random replacement.
  overflow.each { |item| replace!(item) } unless overflow.nil?
end

#empty?Boolean

Return if the buffer is empty.

Returns:

  • (Boolean)


57
58
59
# File 'lib/datadog/core/buffer/random.rb', line 57

def empty?
  @items.empty?
end

#lengthObject

Return the current number of stored items.



52
53
54
# File 'lib/datadog/core/buffer/random.rb', line 52

def length
  @items.length
end

#popObject

Stored items are returned and the local buffer is reset.



47
48
49
# File 'lib/datadog/core/buffer/random.rb', line 47

def pop
  drain!
end

#push(item) ⇒ Object

Add a new “item“ in the local queue. This method doesn’t block the execution even if the buffer is full.

When the buffer is full, we try to ensure that we are fairly choosing newly pushed items by randomly inserting them into the buffer slots. This discards old items randomly while trying to ensure that recent items are still captured.



24
25
26
27
28
29
# File 'lib/datadog/core/buffer/random.rb', line 24

def push(item)
  return if closed?

  full? ? replace!(item) : add!(item)
  item
end