Class: JSI::Util::MemoMap Private

Inherits:
Object
  • Object
show all
Defined in:
lib/jsi/util.rb

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Defined Under Namespace

Classes: Result

Instance Method Summary collapse

Constructor Details

#initialize(key_by: nil, &block) ⇒ MemoMap

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of MemoMap.


134
135
136
137
138
139
140
141
142
143
144
# File 'lib/jsi/util.rb', line 134

def initialize(key_by: nil, &block)
  @key_by = key_by
  @block = block

  # each result has its own mutex to update its memoized value thread-safely
  @result_mutexes = {}
  # another mutex to thread-safely initialize each result mutex
  @result_mutexes_mutex = Mutex.new

  @results = {}
end

Instance Method Details

#[](*inputs) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.


146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/jsi/util.rb', line 146

def [](*inputs)
  if @key_by
    key = @key_by.call(*inputs)
  else
    key = inputs
  end
  result_mutex = @result_mutexes_mutex.synchronize do
    @result_mutexes[key] ||= Mutex.new
  end

  result_mutex.synchronize do
    inputs_hash = inputs.hash
    if @results.key?(key) && inputs_hash == @results[key].inputs_hash && inputs == @results[key].inputs
      @results[key].value
    else
      value = @block.call(*inputs)
      @results[key] = Result.new(value: value, inputs: inputs, inputs_hash: inputs_hash)
      value
    end
  end
end