Class: Datadog::AppSec::ThreadSafeRef

Inherits:
Object
  • Object
show all
Defined in:
lib/datadog/appsec/thread_safe_ref.rb

Overview

This class is used for referencing an object that might be marked for finalization in another thread.

References to the object are counted, and objects marked for finalization can be safely finalized when their reference count reaches zero.

Instance Method Summary collapse

Constructor Details

#initialize(initial_obj, finalizer: :finalize!) ⇒ ThreadSafeRef

Returns a new instance of ThreadSafeRef.



11
12
13
14
15
16
17
18
# File 'lib/datadog/appsec/thread_safe_ref.rb', line 11

def initialize(initial_obj, finalizer: :finalize!)
  @current = initial_obj
  @finalizer = finalizer

  @counters = Hash.new(0)
  @outdated = []
  @mutex = Mutex.new
end

Instance Method Details

#acquireObject



20
21
22
23
24
25
26
# File 'lib/datadog/appsec/thread_safe_ref.rb', line 20

def acquire
  @mutex.synchronize do
    @counters[@current] += 1

    @current
  end
end

#current=(obj) ⇒ Object



40
41
42
43
44
45
46
# File 'lib/datadog/appsec/thread_safe_ref.rb', line 40

def current=(obj)
  @mutex.synchronize do
    @outdated << @current

    @current = obj
  end
end

#release(obj) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/datadog/appsec/thread_safe_ref.rb', line 28

def release(obj)
  @mutex.synchronize do
    @counters[obj] -= 1

    @outdated.reject! do |outdated_obj|
      next unless @counters[outdated_obj].zero?

      finalize(outdated_obj)
    end
  end
end