Class: MultiJSON::OptionsCache::Store Private
- Inherits:
-
Object
- Object
- MultiJSON::OptionsCache::Store
- Defined in:
- lib/multi_json/options_cache/mutex_store.rb
Overview
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.
Thread-safe cache store backed by a Hash guarded by a Mutex
Used on MRI and TruffleRuby, where a runtime dependency on concurrent-ruby would be overkill: the GVL on MRI makes single lookups atomic, and locking on both reads and writes keeps the small perf cost predictable across engines without adding a runtime dependency.
Instance Method Summary collapse
-
#fetch(key, default = nil) { ... } ⇒ Object
private
Fetch a value from cache or compute it.
-
#initialize ⇒ Store
constructor
private
Create a new cache store.
-
#reset ⇒ void
private
Clear all cached entries.
Constructor Details
#initialize ⇒ Store
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.
Create a new cache store
19 20 21 22 |
# File 'lib/multi_json/options_cache/mutex_store.rb', line 19 def initialize @cache = {} @mutex = Mutex.new end |
Instance Method Details
#fetch(key, default = nil) { ... } ⇒ 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.
Fetch a value from cache or compute it
When called with a block, returns the cached value or computes a
new one. When called without a block, returns the cached value or
the supplied default if the key is missing. Nil cached values are
preserved because Hash#fetch only falls through to the default
block when the key is truly missing. The block_given? check
is hoisted out of the mutex so the no-block read path runs the
check once per call instead of once inside the critical section.
53 54 55 56 57 58 59 60 61 62 |
# File 'lib/multi_json/options_cache/mutex_store.rb', line 53 def fetch(key, default = nil) return @mutex.synchronize { @cache.fetch(key) { default } } unless block_given? @mutex.synchronize do @cache.fetch(key) do @cache.shift if @cache.size >= OptionsCache.max_cache_size @cache[key] = yield end end end |
#reset ⇒ void
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.
This method returns an undefined value.
Clear all cached entries
Held under the mutex because TruffleRuby (which also uses this
backend via the ruby-platform gem) has true parallelism: a
concurrent fetch racing with Hash#clear could corrupt
iteration in a way that MRI's GVL would otherwise prevent.
33 34 35 |
# File 'lib/multi_json/options_cache/mutex_store.rb', line 33 def reset @mutex.synchronize { @cache.clear } end |