Skip to content

Commit

Permalink
minor cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
pitr-ch committed Nov 17, 2019
1 parent e71fa2e commit 4d04a24
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions lib/concurrent/atomic/ruby_thread_local_var.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ class RubyThreadLocalVar < AbstractThreadLocalVar
FREE = []
LOCK = Mutex.new
ARRAYS = {} # used as a hash set
# noinspection RubyClassVariableUsageInspection
@@next = 0
QUEUE = Queue.new
THREAD = Thread.new do
Expand Down Expand Up @@ -62,7 +63,7 @@ class RubyThreadLocalVar < AbstractThreadLocalVar

# @!macro thread_local_var_method_get
def value
if array = get_threadlocal_array
if (array = get_threadlocal_array)
value = array[@index]
if value.nil?
default
Expand All @@ -82,7 +83,7 @@ def value=(value)
# We could keep the thread-local arrays in a hash, keyed by Thread
# But why? That would require locking
# Using Ruby's built-in thread-local storage is faster
unless array = get_threadlocal_array(me)
unless (array = get_threadlocal_array(me))
array = set_threadlocal_array([], me)
LOCK.synchronize { ARRAYS[array.object_id] = array }
ObjectSpace.define_finalizer(me, self.class.thread_finalizer(array.object_id))
Expand All @@ -94,6 +95,7 @@ def value=(value)
protected

# @!visibility private
# noinspection RubyClassVariableUsageInspection
def allocate_storage
@index = LOCK.synchronize do
FREE.pop || begin
Expand All @@ -107,6 +109,7 @@ def allocate_storage

# @!visibility private
def self.thread_local_finalizer(index)
# avoid error: can't be called from trap context
proc { QUEUE.push [:thread_local_finalizer, index] }
end

Expand Down Expand Up @@ -142,21 +145,22 @@ def set_threadlocal_array(array, thread = Thread.current)
# This exists only for use in testing
# @!visibility private
def value_for(thread)
if array = get_threadlocal_array(thread)
if (array = get_threadlocal_array(thread))
value = array[@index]
if value.nil?
default_for(thread)
get_default
elsif value.equal?(NULL)
nil
else
value
end
else
default_for(thread)
get_default
end
end

def default_for(thread)
# @!visibility private
def get_default
if @default_block
raise "Cannot use default_for with default block"
else
Expand Down

0 comments on commit 4d04a24

Please sign in to comment.