Class: Ref::SoftReference
- Defined in:
- lib/ref/soft_reference.rb
Overview
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
Direct Known Subclasses
Constant Summary collapse
- MIN_GC_CYCLES =
Number of garbage collection cycles after an object is used before a reference to it can be reclaimed.
10
- @@strong_references =
[{}]
- @@gc_flag_set =
false
- @@lock =
SafeMonitor.new
- @@finalizer =
lambda do |object_id| @@lock.synchronize do while @@strong_references.size >= MIN_GC_CYCLES do @@strong_references.shift end @@strong_references.push({}) if @@strong_references.size < MIN_GC_CYCLES @@gc_flag_set = false end end
Instance Attribute Summary
Attributes inherited from Reference
Instance Method Summary collapse
-
#initialize(obj) ⇒ SoftReference
constructor
Create a new soft reference to an object.
-
#object ⇒ Object
Get the referenced object.
Methods inherited from Reference
Constructor Details
#initialize(obj) ⇒ SoftReference
Create a new soft reference to an object.
39 40 41 42 43 |
# 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 |
Instance Method Details
#object ⇒ Object
Get the referenced object. If the object has been reclaimed by the garbage collector, then this will return nil.
47 48 49 50 51 52 |
# 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 |