Class: Fontisan::Variation::ThreadSafeCache

Inherits:
Cache
  • Object
show all
Defined in:
lib/fontisan/variation/cache.rb

Overview

Thread-safe cache wrapper

Wraps Cache with Mutex for thread-safe operations.

Instance Attribute Summary

Attributes inherited from Cache

#max_size, #stats

Instance Method Summary collapse

Methods inherited from Cache

#cached?, #empty?, #fetch_instance, #fetch_interpolated, #fetch_region_matches, #fetch_scalars, #full?, #invalidate_matching, #size

Constructor Details

#initialize(max_size: 1000, ttl: nil) ⇒ ThreadSafeCache

Returns a new instance of ThreadSafeCache.



246
247
248
249
# File 'lib/fontisan/variation/cache.rb', line 246

def initialize(max_size: 1000, ttl: nil)
  super
  @mutex = Mutex.new
end

Instance Method Details

#clearObject



288
289
290
# File 'lib/fontisan/variation/cache.rb', line 288

def clear
  @mutex.synchronize { super }
end

#fetch(key) ⇒ Object



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
# File 'lib/fontisan/variation/cache.rb', line 251

def fetch(key)
  # Check cache without entering critical section for computation
  @mutex.synchronize do
    if cached?(key)
      @stats[:hits] += 1
      touch(key)
      return @cache[key][:value]
    end
  end

  # Compute value outside of mutex
  value = yield

  # Store result
  @mutex.synchronize do
    evict_if_needed
    @cache[key] = {
      value: value,
      created_at: Time.now,
    }
    touch(key)
  end

  value
end

#invalidate(key) ⇒ Object



292
293
294
# File 'lib/fontisan/variation/cache.rb', line 292

def invalidate(key)
  @mutex.synchronize { super }
end

#statisticsObject



296
297
298
# File 'lib/fontisan/variation/cache.rb', line 296

def statistics
  @mutex.synchronize { super }
end

#store(key, value) ⇒ Object



277
278
279
280
281
282
283
284
285
286
# File 'lib/fontisan/variation/cache.rb', line 277

def store(key, value)
  @mutex.synchronize do
    evict_if_needed
    @cache[key] = {
      value: value,
      created_at: Time.now,
    }
    touch(key)
  end
end