In Files

  • gc.c

Class/Module Index [+]



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 when a specific object is about to be destroyed by garbage collection.

require 'objspace'

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}" })


Finalizer two on 537763470
Finalizer one on 537763480

Public Class Methods

_id2ref(object_id) → an_object click to toggle source

Converts an object id to a reference to the object. May not be called on an object id passed as a parameter to a finalizer.

s = "I am a string"                    #=> "I am a string"
r = ObjectSpace._id2ref(s.object_id)   #=> "I am a string"
r == s                                 #=> true
               static VALUE
id2ref(VALUE obj, VALUE objid)
#define NUM2PTR(x) NUM2ULONG(x)
#define NUM2PTR(x) NUM2ULL(x)
    rb_objspace_t *objspace = &rb_objspace;
    VALUE ptr;
    VALUE orig;
    void *p0;

    ptr = NUM2PTR(objid);
    p0 = (void *)ptr;

    if (ptr == Qtrue) return Qtrue;
    if (ptr == Qfalse) return Qfalse;
    if (ptr == Qnil) return Qnil;
    if (FIXNUM_P(ptr)) return (VALUE)ptr;
    if (FLONUM_P(ptr)) return (VALUE)ptr;
    ptr = obj_id_to_ref(objid);

    if (st_lookup(objspace->id_to_obj_tbl, ptr, &orig)) {
        return orig;

    if ((ptr % sizeof(RVALUE)) == (4 << 2)) {
        ID symid = ptr / sizeof(RVALUE);
        if (rb_id2str(symid) == 0)
            rb_raise(rb_eRangeError, "%p is not symbol id value", p0);
        return ID2SYM(symid);

    if (!is_id_value(objspace, ptr)) {
        rb_raise(rb_eRangeError, "%p is not id value", p0);
    if (!is_live_object(objspace, ptr)) {
        rb_raise(rb_eRangeError, "%p is recycled object", p0);
    if (RBASIC(ptr)->klass == 0) {
        rb_raise(rb_eRangeError, "%p is internal object", p0);
    return (VALUE)ptr;
count_objects([result_hash]) → hash click to toggle source

Counts all objects grouped by type.

It returns a hash, such as:

  # ...

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 = {}
puts h
# => { :TOTAL=>10000, :T_CLASS=>158280, :T_MODULE=>20672, :T_STRING=>527249 }

This method is only expected to work on C Ruby.

               static VALUE
count_objects(int argc, VALUE *argv, VALUE os)
    rb_objspace_t *objspace = &rb_objspace;
    size_t counts[T_MASK+1];
    size_t freed = 0;
    size_t total = 0;
    size_t i;
    VALUE hash = Qnil;

    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 (i = 0; i <= T_MASK; i++) {
        counts[i] = 0;

    for (i = 0; i < heap_allocated_pages; i++) {
        struct heap_page *page = heap_pages_sorted[i];
        RVALUE *p, *pend;

        p = page->start; pend = p + page->total_slots;
        for (;p < pend; p++) {
            void *poisoned = asan_poisoned_object_p((VALUE)p);
            asan_unpoison_object((VALUE)p, false);
            if (p->as.basic.flags) {
            else {
            if (poisoned) {
                GC_ASSERT(BUILTIN_TYPE((VALUE)p) == T_NONE);
        total += page->total_slots;

    if (hash == Qnil) {
        hash = rb_hash_new();
    else if (!RHASH_EMPTY_P(hash)) {
        rb_hash_stlike_foreach(hash, set_zero, hash);
    rb_hash_aset(hash, ID2SYM(rb_intern("TOTAL")), SIZET2NUM(total));
    rb_hash_aset(hash, ID2SYM(rb_intern("FREE")), SIZET2NUM(freed));

    for (i = 0; i <= T_MASK; i++) {
        VALUE type = type_sym(i);
        if (counts[i])
            rb_hash_aset(hash, type, SIZET2NUM(counts[i]));

    return hash;
define_finalizer(obj, aProc=proc()) click to toggle source

Adds aProc as a finalizer, to be called after obj was destroyed. The object ID of the obj will be passed as an argument to aProc. If aProc is a lambda or method, make sure it can be called with a single argument.

               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();
    else {

    return define_final0(obj, block);
each_object([module]) {|obj| ... } → integer click to toggle source
each_object([module]) → an_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 (Fixnums, Symbols true, false, and nil) are never returned. In the example below, each_object returns both the numbers we defined and several constants defined in the Math module.

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

a = 102.7
b = 95       # Won't be returned
c = 12345678987654321
count = ObjectSpace.each_object(Numeric) {|x| p x }
puts "Total count: #{count}"


Total count: 7
               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);
start → nil click to toggle source
garbage_collect → nil
include GC; garbage_collect → nil
start(full_mark: true, immediate_sweep: true) → nil
garbage_collect(full_mark: true, immediate_sweep: true) → nil
include GC; garbage_collect(full_mark: true, immediate_sweep: true) → nil

Initiates garbage collection, even if manually disabled.

This method is defined with keyword arguments that default to true:

def GC.start(full_mark: true, immediate_sweep: true); end

Use full_mark: false to perform a minor GC. Use immediate_sweep: false to defer sweeping (use lazy sweep).

Note: These keyword arguments are implementation and version dependent. They are not guaranteed to be future-compatible, and may be ignored if the underlying implementation does not support them.

               static VALUE
gc_start_internal(int argc, VALUE *argv, VALUE self)
    rb_objspace_t *objspace = &rb_objspace;
    VALUE opt = Qnil;
    static ID keyword_ids[3];

    rb_scan_args(argc, argv, "0:", &opt);

    if (!NIL_P(opt)) {
        VALUE kwvals[3];

        if (!keyword_ids[0]) {
            keyword_ids[0] = rb_intern("full_mark");
            keyword_ids[1] = rb_intern("immediate_mark");
            keyword_ids[2] = rb_intern("immediate_sweep");

        rb_get_kwargs(opt, keyword_ids, 0, 3, kwvals);

        if (kwvals[0] != Qundef && !RTEST(kwvals[0])) {
            reason &= ~GPR_FLAG_FULL_MARK;
        if (kwvals[1] != Qundef && !RTEST(kwvals[1])) {
            reason &= ~GPR_FLAG_IMMEDIATE_MARK;
        if (kwvals[2] != Qundef && !RTEST(kwvals[2])) {
            reason &= ~GPR_FLAG_IMMEDIATE_SWEEP;

    garbage_collect(objspace, reason);

    return Qnil;
undefine_finalizer(obj) click to toggle source

Removes all finalizers for obj.

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