class RDF::Util::Cache::WeakRefCache

This implementation uses the `WeakRef` class from Ruby's standard library, and provides adequate performance on JRuby and on Ruby 2.x.

@see ruby-doc.org/stdlib-2.2.0/libdoc/weakref/rdoc/WeakRef.html

Public Class Methods

new(capacity = -1) click to toggle source

@param [Integer] capacity

Calls superclass method RDF::Util::Cache.new
# File lib/rdf/util/cache.rb, line 109
def initialize(capacity = -1)
  require 'weakref' unless defined?(::WeakRef)
  super
end

Public Instance Methods

[](key) click to toggle source

@param [Object] key @return [Object]

# File lib/rdf/util/cache.rb, line 117
def [](key)
  if (ref = @cache[key])
    if ref.weakref_alive?
      value = ref.__getobj__ rescue nil
    else
      @cache.delete(key)
      nil
    end
  end
end
[]=(key, value) click to toggle source

@param [Object] key @param [Object] value @return [Object]

# File lib/rdf/util/cache.rb, line 132
def []=(key, value)
  if has_capacity?
    @cache[key] = WeakRef.new(value)
  end
  value
end
delete(key) click to toggle source

Remove cache entry for key

@param [Object] key @return [Object] the previously referenced object

# File lib/rdf/util/cache.rb, line 144
def delete(key)
  ref = @cache.delete(key)
  ref.__getobj__ rescue nil
end