Class: I18n::Tasks::Concurrent::CachedValue

Inherits:
Object
  • Object
show all
Defined in:
lib/i18n/tasks/concurrent/cached_value.rb

Overview

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

Since:

  • 0.9.25

Constant Summary collapse

NULL =

Since:

  • 0.9.25

Object.new

Instance Method Summary collapse

Constructor Details

#initialize(&computation) ⇒ CachedValue

Returns a new instance of CachedValue.

Parameters:

  • computation (Proc)

    The computation that returns the value to cache.

Since:

  • 0.9.25



11
12
13
14
15
# File 'lib/i18n/tasks/concurrent/cached_value.rb', line 11

def initialize(&computation)
  @computation = computation
  @mutex = Mutex.new
  @result = NULL
end

Instance Method Details

#getObject

Returns Result of the computation.

Returns:

  • (Object)

    Result of the computation.

Since:

  • 0.9.25



18
19
20
21
22
23
24
25
26
27
28
# 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