Class: Wref

Inherits:
Object
  • Object
show all
Defined in:
lib/wref.rb

Overview

A simple weak-reference framework with mapping. Only handles the referencing of objects.

Examples

user_obj = ob.get(:User, 1) weak_ref = Wref.new(user_obj) user_obj = nil sleep 0.5 GC.start

begin

user_obj = weak_ref.get
print "The user still exists in memory and has ID #{user.id}."

rescue Wref::Recycled

print "The user has been removed from memory."

end

Defined Under Namespace

Classes: Implementations, Map, Recycled

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, args = {}) ⇒ Wref

Initializes various variables.



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/wref.rb', line 36

def initialize(object, args = {})
  if args[:impl]
    @implementation = args[:impl]
  elsif RUBY_ENGINE == "jruby"
    @implementation = :JavaWeakReference
  else
    @implementation = :IdClassUnique
  end

  @weak_ref = Wref::Implementations.const_get(implementation).new(object)
end

Instance Attribute Details

#implementationObject (readonly)

Returns the value of attribute implementation.



33
34
35
# File 'lib/wref.rb', line 33

def implementation
  @implementation
end

#weak_refObject (readonly)

Returns the value of attribute weak_ref.



33
34
35
# File 'lib/wref.rb', line 33

def weak_ref
  @weak_ref
end

Instance Method Details

#alive?Boolean Also known as: weakref_alive?

Returns true if the reference is still alive. print “The object still exists in memory.” if wref.alive?

Returns:

  • (Boolean)


66
67
68
# File 'lib/wref.rb', line 66

def alive?
  @weak_ref.alive?
end

#getObject Also known as: __getobj__

The same as the normal ‘get!’ but returns nil instead of raising Wref::Cycled-error.



60
61
62
# File 'lib/wref.rb', line 60

def get
  @weak_ref.get
end

#get!Object

Returns the object that this weak reference holds or raises Wref::Recycled. begin

object = wref.get!
puts "Object still exists in memory."

rescue Wref::Recycled

puts "Object has been garbage-collected."

end



55
56
57
# File 'lib/wref.rb', line 55

def get!
  @weak_ref.get!
end