Ruby leaked objects are referenced by RubyVm::Env

405 views Asked by At

I am tracing a memory leak problem in our application (ruby 2.1). I am using both techniques: ObjectSpace.dump_all for dumping all objects to JSON stream then do an offline analysis. The second technique I used is live analysis with ObjectSpace.reachable_objects_from. In both ways, I found that my leaked objects are referenced by an object RubyVM::Env. Anyone could explain to me what is RubyVM::Env. How to remove those references?

1

There are 1 answers

0
Jacob Dam On BEST ANSWER

RubyVM::Env is an internal ruby class that holds variable references. Here is my test:

require 'objspace'

a = Object.new
a_id = a.object_id # we use #object_id to avoid creating more reference to `a`

ObjectSpace.each_object.select{ |o| ObjectSpace.reachable_objects_from(o).map(&:object_id).include?(a_id) }.count
# => 1

env = ObjectSpace.each_object.select{ |o| ObjectSpace.reachable_objects_from(o).map(&:object_id).include?(a_id) }.first
# => #<RubyVM::Env:0x007ff39ac09a78>

ObjectSpace.reachable_objects_from(env).count
# => 5

a = nil # remove reference

ObjectSpace.reachable_objects_from(env).count
# => 4