Class: RDF::Util::Cache

Inherits:
Object
  • Object
show all
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 and Spira. Do be sure to include any changes here in the RDF.rb changelog.

See Also:

Since:

Direct Known Subclasses

ObjectSpaceCache, WeakRefCache

Defined Under Namespace

Classes: ObjectSpaceCache, WeakRefCache

Instance Method Summary (collapse)

Constructor Details

- (Cache) initialize(capacity = 1)

A new instance of Cache

Parameters:

  • capacity (Integer) (defaults to: 1)

Since:

  • 0.2.0



37
38
39
40
41
# File 'lib/rdf/util/cache.rb', line 37

def initialize(capacity = -1)
  @capacity = capacity
  @cache  ||= {}
  @index  ||= {}
end

Instance Method Details

- define_finalizer!(value)

This method returns an undefined value.

Parameters:

  • value (Object)

Since:

  • 0.2.0



58
59
60
# File 'lib/rdf/util/cache.rb', line 58

def define_finalizer!(value)
  ObjectSpace.define_finalizer(value, finalizer)
end

- (Proc) finalizer

Returns:

  • (Proc)

Since:

  • 0.2.0



64
65
66
# File 'lib/rdf/util/cache.rb', line 64

def finalizer
  lambda { |object_id| @cache.delete(@index.delete(object_id)) }
end

- (Boolean) has_capacity?

Returns:

  • (Boolean)

Since:

  • 0.2.0



51
52
53
# File 'lib/rdf/util/cache.rb', line 51

def has_capacity?
  @capacity.equal?(-1) || @capacity > @cache.size
end

- (Integer) size

Returns:

  • (Integer)

Since:

  • 0.2.0



45
46
47
# File 'lib/rdf/util/cache.rb', line 45

def size
  @cache.size
end