Class: Google::Protobuf::ObjectCache

Inherits:
Object
  • Object
show all
Defined in:
lib/google/protobuf/object_cache.rb

Overview

A pointer -> Ruby Object cache that keeps references to Ruby wrapper objects. This allows us to look up any Ruby wrapper object by the address of the object it is wrapping. That way we can avoid ever creating two different wrapper objects for the same C object, which saves memory and preserves object identity.

We use WeakMap for the cache. If sizeof(long) > sizeof(VALUE), we also need a secondary Hash to store WeakMap keys, because our pointer keys may need to be stored as Bignum instead of Fixnum. Since WeakMap is weak for both keys and values, a Bignum key will cause the WeakMap entry to be collected immediately unless there is another reference to the Bignum. This happens on 64-bit Windows, on which pointers are 64 bits but longs are 32 bits. In this case, we enable the secondary Hash to hold the keys and prevent them from being collected.

Instance Method Summary collapse

Constructor Details

#initializeObjectCache

Returns a new instance of ObjectCache.



25
26
27
28
# File 'lib/google/protobuf/object_cache.rb', line 25

def initialize
  @map = ObjectSpace::WeakMap.new
  @mutex = Mutex.new
end

Instance Method Details

#get(key) ⇒ Object



30
31
32
# File 'lib/google/protobuf/object_cache.rb', line 30

def get(key)
  @map[key]
end

#try_add(key, value) ⇒ Object



34
35
36
37
38
# File 'lib/google/protobuf/object_cache.rb', line 34

def try_add(key, value)
  @map[key] || @mutex.synchronize do
    @map[key] ||= value
  end
end