class Ref::SoftReference
A SoftReference represents a reference to an object that is not seen by the tracing phase of the garbage collector. This allows the referenced object to be garbage collected as if nothing is referring to it.
A SoftReference differs from a WeakReference in that the garbage collector is not so eager to reclaim soft references so they should persist longer.
Example usage:¶ ↑
foo = Object.new ref = Ref::SoftReference.new(foo) ref.object # should be foo ObjectSpace.garbage_collect ref.object # should be foo ObjectSpace.garbage_collect ObjectSpace.garbage_collect ref.object # should be nil
Constants
- MIN_GC_CYCLES
Number of garbage collection cycles after an object is used before a reference to it can be reclaimed.
Public Class Methods
new(obj)
click to toggle source
Create a new soft reference to an object.
# File lib/ref/soft_reference.rb, line 39 def initialize(obj) @referenced_object_id = obj.__id__ @weak_reference = WeakReference.new(obj) add_strong_reference(obj) end
Public Instance Methods
object()
click to toggle source
Get the referenced object. If the object has been reclaimed by the garbage collector, then this will return nil.
# File lib/ref/soft_reference.rb, line 47 def object obj = @weak_reference.object # add a temporary strong reference each time the object is referenced. add_strong_reference(obj) if obj obj end