Class: Google::Protobuf::LegacyObjectCache
- Inherits:
-
Object
- Object
- Google::Protobuf::LegacyObjectCache
- Defined in:
- lib/google/protobuf/object_cache.rb
Instance Method Summary collapse
- #get(key) ⇒ Object
-
#initialize ⇒ LegacyObjectCache
constructor
A new instance of LegacyObjectCache.
- #try_add(key, value) ⇒ Object
Constructor Details
#initialize ⇒ LegacyObjectCache
Returns a new instance of LegacyObjectCache.
42 43 44 45 46 |
# File 'lib/google/protobuf/object_cache.rb', line 42 def initialize @secondary_map = {} @map = ObjectSpace::WeakMap.new @mutex = Mutex.new end |
Instance Method Details
#get(key) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/google/protobuf/object_cache.rb', line 48 def get(key) value = if secondary_key = @secondary_map[key] @map[secondary_key] else @mutex.synchronize do @map[(@secondary_map[key] ||= Object.new)] end end # GC if we could remove at least 2000 entries or 20% of the table size # (whichever is greater). Since the cost of the GC pass is O(N), we # want to make sure that we condition this on overall table size, to # avoid O(N^2) CPU costs. cutoff = (@secondary_map.size * 0.2).ceil cutoff = 2_000 if cutoff < 2_000 if (@secondary_map.size - @map.size) > cutoff purge end value end |
#try_add(key, value) ⇒ Object
70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/google/protobuf/object_cache.rb', line 70 def try_add(key, value) if secondary_key = @secondary_map[key] if old_value = @map[secondary_key] return old_value end end @mutex.synchronize do secondary_key ||= (@secondary_map[key] ||= Object.new) @map[secondary_key] ||= value end end |