123456789_123456789_123456789_123456789_123456789_

Module: ObjectSpace

Relationships & Source Files
Namespace Children
Classes:
Defined in: gc.c,
gc.rb,
weakmap.c

Overview

The ObjectSpace module contains a number of routines that interact with the garbage collection facility and allow you to traverse all living objects with an iterator.

ObjectSpace also provides support for object finalizers, procs that will be called after a specific object was destroyed by garbage collection. See the documentation for .define_finalizer for important information on how to use this method correctly.

a = "A"
b = "B"

ObjectSpace.define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
ObjectSpace.define_finalizer(b, proc {|id| puts "Finalizer two on #{id}" })

a = nil
b = nil

produces:

Finalizer two on 537763470
Finalizer one on 537763480

Class Method Summary

Class Method Details

._id2ref(objid) (mod_func)

This method is for internal use only.
[ GitHub ]

  
# File 'gc.c', line 2344

static VALUE
os_id2ref(VALUE os, VALUE objid)
{
    rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "ObjectSpace._id2ref is deprecated");
    return id2ref(objid);
}

.count_objects([result_hash]) ⇒ Hash (mod_func)

Counts all objects grouped by type.

It returns a hash, such as:

{
  :TOTAL=>10000,
  :FREE=>3011,
  :T_OBJECT=>6,
  :T_CLASS=>404,
  # ...
}

The contents of the returned hash are implementation specific. It may be changed in future.

The keys starting with :T_ means live objects. For example, :T_ARRAY is the number of arrays. :FREE means object slots which is not used now. :TOTAL means sum of above.

If the optional argument result_hash is given, it is overwritten and returned. This is intended to avoid probe effect.

h = {}
ObjectSpace.count_objects(h)
puts h
# => { :TOTAL=>10000, :T_CLASS=>158280, :T_MODULE=>20672, :T_STRING=>527249 }

This method is only expected to work on C Ruby.

[ GitHub ]

  
# File 'gc.c', line 2658

static VALUE
count_objects(int argc, VALUE *argv, VALUE os)
{
    struct count_objects_data data = { 0 };
    VALUE hash = Qnil;
    VALUE types[T_MASK + 1];

    if (rb_check_arity(argc, 0, 1) == 1) {
        hash = argv[0];
        if (!RB_TYPE_P(hash, T_HASH))
            rb_raise(rb_eTypeError, "non-hash given");
    }

    for (size_t i = 0; i <= T_MASK; i++) {
        // type_sym can allocate an object,
        // so we need to create all key symbols in advance
        // not to disturb the result
        types[i] = type_sym(i);
    }

    // Same as type_sym, we need to create all key symbols in advance
    VALUE total = ID2SYM(rb_intern("TOTAL"));
    VALUE free = ID2SYM(rb_intern("FREE"));

    rb_gc_impl_each_object(rb_gc_get_objspace(), count_objects_i, &data);

    if (NIL_P(hash)) {
        hash = rb_hash_new();
    }
    else if (!RHASH_EMPTY_P(hash)) {
        rb_hash_stlike_foreach(hash, set_zero, hash);
    }
    rb_hash_aset(hash, total, SIZET2NUM(data.total));
    rb_hash_aset(hash, free, SIZET2NUM(data.freed));

    for (size_t i = 0; i <= T_MASK; i++) {
        if (data.counts[i]) {
            rb_hash_aset(hash, types[i], SIZET2NUM(data.counts[i]));
        }
    }

    return hash;
}

.define_finalizer(obj) {|id| ... } ⇒ Array (mod_func) .define_finalizer(obj, finalizer) ⇒ Array

Adds a new finalizer for obj that is called when obj is destroyed by the garbage collector or when ::Ruby shuts down (which ever comes first).

With a block given, uses the block as the callback. Without a block given, uses a callable object finalizer as the callback. The callback is called when obj is destroyed with a single argument id which is the object ID of obj (see Object#object_id).

The return value is an array [0, callback], where callback is a ::Proc created from the block if one was given or finalizer otherwise.

Note that defining a finalizer in an instance method of the object may prevent the object from being garbage collected since if the block or finalizer refers to obj then obj will never be reclaimed by the garbage collector. For example, the following script demonstrates the issue:

class Foo
  def define_final
    ObjectSpace.define_finalizer(self) do |id|
      puts "Running finalizer for #{id}!"
    end
  end
end

obj = Foo.new
obj.define_final

There are two patterns to solve this issue:

  • Create the finalizer in a non-instance method so it can safely capture the needed state:

    class Foo
      def define_final
        ObjectSpace.define_finalizer(self, self.class.create_finalizer)
      end
    
      def self.create_finalizer
        proc do |id|
          puts "Running finalizer for #{id}!"
        end
      end
    end
  • Use a callable object:

    class Foo
      class Finalizer
        def call(id)
          puts "Running finalizer for #{id}!"
        end
      end
    
      def define_final
        ObjectSpace.define_finalizer(self, Finalizer.new)
      end
    end

Note that finalization can be unpredictable and is never guaranteed to be run except on exit.

[ GitHub ]

  
# File 'gc.c', line 1885

static VALUE
define_final(int argc, VALUE *argv, VALUE os)
{
    VALUE obj, block;

    rb_scan_args(argc, argv, "11", &obj, &block);
    if (argc == 1) {
        block = rb_block_proc();
    }

    if (rb_callable_receiver(block) == obj) {
        rb_warn("finalizer references object to be finalized");
    }

    return rb_define_finalizer(obj, block);
}

.each_object([module]) {|obj| ... } ⇒ Integer (mod_func) .each_object([module]) ⇒ Enumerator

Calls the block once for each living, nonimmediate object in this ::Ruby process. If module is specified, calls the block for only those classes or modules that match (or are a subclass of) module. Returns the number of objects found. Immediate objects (such as Fixnums, static ::Symbols true, false and nil) are never returned.

If no block is given, an enumerator is returned instead.

Job = Class.new
jobs = [Job.new, Job.new]
count = ObjectSpace.each_object(Job) {|x| p x }
puts "Total count: #{count}"

produces:

#<Job:0x000000011d6cbbf0>
#<Job:0x000000011d6cbc68>
 Total count: 2

Due to a current ::Ractor implementation issue, this method does not yield Ractor-unshareable objects when the process is in multi-Ractor mode. Multi-ractor mode is enabled when Ractor.new has been called for the first time. See bugs.ruby-lang.org/issues/19387 for more information.

a = 12345678987654321 # shareable
b = [].freeze # shareable
c = {} # not shareable
ObjectSpace.each_object {|x| x } # yields a, b, and c
Ractor.new {} # enter multi-Ractor mode
ObjectSpace.each_object {|x| x } # does not yield c
[ GitHub ]

  
# File 'gc.c', line 1759

static VALUE
os_each_obj(int argc, VALUE *argv, VALUE os)
{
    VALUE of;

    of = (!rb_check_arity(argc, 0, 1) ? 0 : argv[0]);
    RETURN_ENUMERATOR(os, 1, &of);
    return os_obj_of(of);
}

.garbage_collect(full_mark: true, immediate_mark: true, immediate_sweep: true) (mod_func)

Alias of GC.start

[ GitHub ]

  
# File 'gc.rb', line 594

def garbage_collect full_mark: true, immediate_mark: true, immediate_sweep: true
  Primitive.gc_start_internal full_mark, immediate_mark, immediate_sweep, false
end

.undefine_finalizer(obj) (mod_func)

Removes all finalizers for obj.

[ GitHub ]

  
# File 'gc.c', line 1777

static VALUE
undefine_final(VALUE os, VALUE obj)
{
    return rb_undefine_finalizer(obj);
}