class I18n::Tasks::Concurrent::CachedValue

A thread-safe memoized value. The given computation is guaranteed to be invoked at most once. @since 0.9.25

Constants

NULL

Public Class Methods

new(&computation) click to toggle source

@param [Proc] computation The computation that returns the value to cache.

# File lib/i18n/tasks/concurrent/cached_value.rb, line 11
def initialize(&computation)
  @computation = computation
  @mutex = Mutex.new
  @result = NULL
end

Public Instance Methods

get() click to toggle source

@return [Object] Result of the computation.

# File lib/i18n/tasks/concurrent/cached_value.rb, line 18
def get
  return get_result_volatile unless get_result_volatile == NULL

  @mutex.synchronize do
    next unless get_result_volatile == NULL

    set_result_volatile @computation.call
    @computation = nil
  end
  get_result_volatile
end

Private Instance Methods

get_result_volatile() click to toggle source
# File lib/i18n/tasks/concurrent/cached_value.rb, line 39
def get_result_volatile
  Rubinius.memory_barrier
  @result
end
set_result_volatile(value) click to toggle source
# File lib/i18n/tasks/concurrent/cached_value.rb, line 44
def set_result_volatile(value)
  @result = value
  Rubinius.memory_barrier
end