Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 134 ยท Standard Library

ObjectSpace, WeakRef and the Garbage Collector

Learn how Ruby's garbage collector works - GC.stat and GC.start, ObjectSpace.each_object, finalizers, WeakRef, ObjectSpace::WeakMap and WeakKeyMap, and when to tune GC.

You never free memory by hand in Ruby. When an object can no longer be reached from your program, the garbage collector (GC) reclaims it. Most of the time you can ignore this completely. But long-running servers, caches and tools that hold many objects eventually raise questions: why is memory growing, how do I attach cleanup to an object, how can a cache hold objects without keeping them alive?

Ruby answers these with three small toolkits: the GC module (control and statistics), ObjectSpace (inspect and count live objects, attach finalizers) and weak references (WeakRef, ObjectSpace::WeakMap, ObjectSpace::WeakKeyMap). This lesson shows each one, and is honest about what is deterministic: the moment an object is collected is not something you should depend on, so the examples below print only facts that always hold.

How the collector decides what to free

The GC starts from a set of roots: global variables, constants, local variables on the stack, and so on. Everything reachable from a root is live. Everything else is garbage. CRuby uses a mark and sweep collector with generations: young objects are checked often, objects that survived several collections are promoted to the old generation and checked rarely.

flowchart LR
  R["Roots<br/>(locals, constants, globals)"] --> A["Object A"]
  A --> B["Object B"]
  R --> C["Object C"]
  D["Object D"] --> E["Object E"]
  classDef dead stroke-dasharray: 4 3
  class D,E dead

Objects A, B and C can be reached from a root and survive; D and E are only referenced from each other, so the next collection frees them.

Objects that refer to each other in a cycle are still freed when nothing outside the cycle points to them. A mark-and-sweep GC does not need reference counting, so cycles are not a leak.

Talking to the GC

GC.start runs a collection now. GC.count says how many have happened, and GC.stat returns a hash of counters. You rarely call GC.start in production code, but it is useful in experiments and tests.

Ruby GC.start, GC.count and GC.stat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

GC.disable returns whether the GC was already disabled, which is why the second call prints true. Disabling the collector is almost never a good idea in a server, but a short script that builds a large structure and exits can sometimes finish faster with the GC off.

Counting and finding objects with ObjectSpace

ObjectSpace lets you look at the heap. ObjectSpace.count_objects returns counters by type, and ObjectSpace.each_object(SomeClass) yields every live object of that class, including Class and Module objects themselves. This is how tools find "all subclasses of X" or hunt leaks.

Ruby Finding live objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A note on the last line: after keep.clear the three widgets are eligible for collection, but CRuby scans the machine stack conservatively, so a stale reference in a register can keep one alive a little longer. That is why the example says "never more than" instead of promising zero. This is a theme in the whole lesson: you can ask for a collection, but you cannot ask for a particular object to die.

For finding subclasses you now have a better tool: Class#subclasses (see Class Hooks). ObjectSpace is the general instrument; use it in debugging, not in application logic.

Finalizers: code that runs when an object goes away

ObjectSpace.define_finalizer(object, callable) registers a proc that runs after object has been collected, or at the latest when the process exits. Two rules make them tricky:

  1. The callable receives the object's id, not the object (the object is already gone).
  2. The callable must not capture the object itself. If the proc closes over it, the object stays reachable forever and is never collected.
Ruby A safe finalizer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Because you cannot know when, finalizers suit last-resort cleanup (closing a file descriptor that a forgotten object owned). For anything that matters, give the object an explicit close method and use the ensure or block pattern from Exceptions. Ruby's own File.open with a block is the model: the cleanup is deterministic and the finalizer is only a safety net.

ObjectSpace.undefine_finalizer(object) removes finalizers that you registered, for the case where an explicit close already did the work.

WeakRef: a reference that does not keep the object alive

A normal reference keeps its target alive. A weak reference does not: the GC may free the target, and the reference then tells you so. The standard library provides WeakRef (require "weakref"). It wraps an object and forwards method calls to it, until the object is gone and every call raises WeakRef::RefError.

Ruby WeakRef basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A typical use is an optional cache: you remember a computed value cheaply, but you do not force the program to hold on to it when memory is tight. Always check weakref_alive? or rescue WeakRef::RefError, and copy the object into a normal local variable before using it a few times, otherwise it can disappear between two lines.

WeakMap and WeakKeyMap: caches that clean themselves

For caches, WeakRef per entry gets clumsy. Ruby has two weak containers in the core.

  • ObjectSpace::WeakMap holds weak keys and weak values. An entry disappears as soon as either side is collected. Keys are compared by identity.
  • ObjectSpace::WeakKeyMap holds weak keys and strong values, and compares keys with eql?/hash like a normal Hash. It is made for caches that look up by a value-equal key but should forget the entry once the original key object is gone.
Ruby WeakMap and WeakKeyMap

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

WeakKeyMap supports a small API on purpose: [], []=, delete, key?, getkey, clear and inspect. It cannot be iterated, because entries might vanish while you loop. Values are held strongly, so a value must never point back at its own key, or the key can never be collected.

Tuning: what to touch and what to leave alone

The defaults suit most programs. When you do need to look closer, work in this order:

  1. Measure. GC.stat shows count, total_allocated_objects, heap_live_slots and malloc_increase_bytes. Time spent in GC can be read from GC.total_time (nanoseconds).
  2. Allocate less. Fewer objects beat any setting. See Benchmarking for counting allocations, and Performance Tips.
  3. Use environment variables for production tuning, set before the process starts. RUBY_GC_HEAP_INIT_SLOTS and RUBY_GC_HEAP_GROWTH_FACTOR control how big the heap starts and how fast it grows; RUBY_GC_MALLOC_LIMIT controls how much non-object memory triggers a collection. Changing them can help a server that spends too much time in collections, and make memory worse if guessed.
  4. Compaction (GC.compact) moves objects together to reduce fragmentation. It exists on platforms that support it; call GC.respond_to?(:compact) and be ready for it to raise NotImplementedError.
Ruby
# read-only example: typical production knobs (set in the shell, not in Ruby)
#   RUBY_GC_HEAP_INIT_SLOTS=600000 \
#   RUBY_GC_HEAP_GROWTH_FACTOR=1.25 \
#   ruby server.rb
Ruby Reading the collector's own numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

GC.stress = true forces a collection very often and is a debugging tool for C extensions, far too slow for normal use.

Common mistakes

  • Relying on finalizer timing. They run late, or only at exit. Provide an explicit close.
  • Capturing the object in the finalizer proc. The object is then never freed.
  • Calling GC.start "to be safe". It stops the world and makes programs slower.
  • Using WeakRef as a general cache without handling RefError.
  • Treating ObjectSpace.each_object as application logic. It walks the whole heap and is slow; use it in debugging and tools.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the garbage collector consider live?

    Mark and sweep starts at the roots and marks everything it can reach. The rest is garbage, even when objects refer to each other in a cycle.
  2. 2. What does the proc passed to ObjectSpace.define_finalizer receive?

    The object is already gone when the finalizer runs, so the proc gets its id. A proc that captures the object would keep it alive.
  3. 3. Which tool fits a cache that looks up by a value-equal key and forgets entries when the key object dies?

    WeakKeyMap compares keys with eql? and hash like a Hash but holds the keys weakly. WeakMap compares by identity.
  4. 4. Why should important cleanup not depend on a finalizer?

    The collector decides when to run finalizers. Use an explicit close or an ensure block and keep the finalizer as a safety net.

Summary

  • The GC frees objects that cannot be reached from the roots; cycles are not leaks.
  • GC.start, GC.count, GC.stat and GC.total_time control and measure it; prefer allocating less over tuning.
  • ObjectSpace.each_object and count_objects inspect the heap for debugging.
  • Finalizers receive an id, must not capture the object, and have no guaranteed timing; use explicit cleanup first.
  • WeakRef, ObjectSpace::WeakMap and ObjectSpace::WeakKeyMap refer to objects without keeping them alive.

Next: Zlib, Open3 and Net::HTTP