class RDF::Util::Cache

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](ruby-rdf/sparql/) and [Spira](spira.rubyforge.org/). Do be sure to include any changes here in the RDF.rb changelog.

@see RDF::URI.intern @see en.wikipedia.org/wiki/Weak_reference @since 0.2.0

Public Class Methods

new(*args) click to toggle source

@private

# 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
new(capacity = -1) click to toggle source

@param [Integer] capacity

# File lib/rdf/util/cache.rb, line 39
def initialize(capacity = -1)
  @capacity = capacity
  @cache  ||= {}
  @index  ||= {}
end

Public Instance Methods

has_capacity?() click to toggle source

@return [Boolean]

# File lib/rdf/util/cache.rb, line 53
def has_capacity?
  @capacity.equal?(-1) || @capacity > @cache.size
end
size() click to toggle source

@return [Integer]

# File lib/rdf/util/cache.rb, line 47
def size
  @cache.size
end