Skip to content

Commit

Permalink
fix: avoid race condition in singleton instance method
Browse files Browse the repository at this point in the history
  • Loading branch information
zvkemp committed Dec 18, 2024
1 parent 743796d commit 18dc263
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,9 @@ class << self
integer: ->(v) { v.is_a?(Integer) },
string: ->(v) { v.is_a?(String) }
}.freeze
SINGLETON_MUTEX = Thread::Mutex.new

private_constant :NAME_REGEX, :VALIDATORS
private_constant :NAME_REGEX, :VALIDATORS, :SINGLETON_MUTEX

private :new

Expand Down Expand Up @@ -163,8 +164,10 @@ def option(name, default:, validate:)
end

def instance
@instance ||= new(instrumentation_name, instrumentation_version, install_blk,
present_blk, compatible_blk, options)
@instance || SINGLETON_MUTEX.synchronize do
@instance ||= new(instrumentation_name, instrumentation_version, install_blk,
present_blk, compatible_blk, options)
end
end

private
Expand Down
24 changes: 24 additions & 0 deletions instrumentation/base/test/instrumentation/base_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,33 @@ def initialize(*args)
end

describe '.instance' do
let(:instrumentation) do
Class.new(OpenTelemetry::Instrumentation::Base) do
instrumentation_name 'test_instrumentation'
instrumentation_version '0.1.1'

def initialize(*args)
# Simulate latency by hinting the VM should switch tasks
# (this can also be accomplished by something like `sleep(0.1)`).
# This replicates the worst-case scenario when using default assignment
# to obtain a singleton, i.e. that the scheduler switches threads between
# the nil check and object initialization.
Thread.pass
super
end
end
end

it 'returns an instance' do
_(instrumentation.instance).must_be_instance_of(instrumentation)
end

it 'returns the same singleton instance to every thread' do
object_ids = Array.new(2).map { Thread.new { instrumentation.instance } }
.map { |thr| thr.join.value }

_(object_ids.uniq.count).must_equal(1)
end
end

describe '.option' do
Expand Down

0 comments on commit 18dc263

Please sign in to comment.