Class: RDF::Util::Cache::WeakRefCache

Inherits:
RDF::Util::Cache show all
Defined in:
lib/rdf/util/cache.rb

Overview

This implementation uses the ‘WeakRef` class from Ruby’s standard library, and provides adequate performance on JRuby and on Ruby 1.9.x; however, it performs very suboptimally on Ruby 1.8.x.

Instance Method Summary collapse

Methods inherited from RDF::Util::Cache

#define_finalizer!, #finalizer, #has_capacity?, new, #size

Constructor Details

#initialize(capacity = -1)) ⇒ WeakRefCache

Returns a new instance of WeakRefCache.

Parameters:

  • capacity (Integer) (defaults to: -1))

Since:

  • 0.2.0



111
112
113
114
# File 'lib/rdf/util/cache.rb', line 111

def initialize(capacity = -1)
  require 'weakref' unless defined?(::WeakRef)
  super
end

Instance Method Details

#[](key) ⇒ Object

Parameters:

  • key (Object)

Returns:

  • (Object)

Since:

  • 0.2.0



119
120
121
122
123
# File 'lib/rdf/util/cache.rb', line 119

def [](key)
  if (ref = @cache[key]) && ref.weakref_alive?
    value = ref.__getobj__ rescue nil
  end
end

#[]=(key, value) ⇒ Object

Parameters:

  • key (Object)
  • value (Object)

Returns:

  • (Object)

Since:

  • 0.2.0



129
130
131
132
133
134
135
136
# File 'lib/rdf/util/cache.rb', line 129

def []=(key, value)
  if has_capacity?
    @cache[key] = WeakRef.new(value)
    @index[value.__id__] = key
    define_finalizer!(value)
  end
  value
end