Class: RDF::Util::Cache
- Inherits:
-
Object
- Object
- RDF::Util::Cache
- Defined in:
- lib/rdf/util/cache.rb
Overview
A ‘Hash`-like cache that holds only weak references to the values it caches, meaning that values contained in the cache can be garbage collected. This allows the cache to dynamically adjust to changing memory conditions, caching more objects when memory is plentiful, but evicting most objects if memory pressure increases to the point of scarcity.
While this cache is something of an internal implementation detail of RDF.rb, some external libraries do currently make use of it as well, including [SPARQL::Algebra](sparql.rubyforge.org/algebra/) and [Spira](spira.rubyforge.org/). Do be sure to include any changes here in the RDF.rb changelog.
Direct Known Subclasses
Defined Under Namespace
Classes: ObjectSpaceCache, WeakRefCache
Class Method Summary collapse
Instance Method Summary collapse
- #define_finalizer!(value) ⇒ void
- #finalizer ⇒ Proc
- #has_capacity? ⇒ Boolean
-
#initialize(capacity = -1)) ⇒ Cache
constructor
A new instance of Cache.
- #size ⇒ Integer
Constructor Details
#initialize(capacity = -1)) ⇒ Cache
Returns a new instance of Cache.
39 40 41 42 43 |
# File 'lib/rdf/util/cache.rb', line 39 def initialize(capacity = -1) @capacity = capacity @cache ||= {} @index ||= {} end |
Class Method Details
.new(*args) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/rdf/util/cache.rb', line 22 def self.new(*args) # JRuby doesn't support `ObjectSpace#_id2ref` unless the `-X+O` # startup option is given. In addition, ObjectSpaceCache is very slow # on Rubinius. On those platforms we'll default to using # the WeakRef-based cache: if RUBY_PLATFORM == 'java' || (defined?(RUBY_ENGINE) && RUBY_ENGINE == 'rbx') klass = WeakRefCache else klass = ObjectSpaceCache end cache = klass.allocate cache.send(:initialize, *args) cache end |
Instance Method Details
#define_finalizer!(value) ⇒ void
This method returns an undefined value.
60 61 62 |
# File 'lib/rdf/util/cache.rb', line 60 def define_finalizer!(value) ObjectSpace.define_finalizer(value, finalizer) end |
#finalizer ⇒ Proc
66 67 68 |
# File 'lib/rdf/util/cache.rb', line 66 def finalizer lambda { |object_id| @cache.delete(@index.delete(object_id)) } end |
#has_capacity? ⇒ Boolean
53 54 55 |
# File 'lib/rdf/util/cache.rb', line 53 def has_capacity? @capacity.equal?(-1) || @capacity > @cache.size end |
#size ⇒ Integer
47 48 49 |
# File 'lib/rdf/util/cache.rb', line 47 def size @cache.size end |