Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby leaked objects are referenced by RubyVm::Env

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?

like image 610
Jacob Dam Avatar asked Jun 09 '15 03:06

Jacob Dam


1 Answers

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
like image 92
Jacob Dam Avatar answered Nov 01 '22 18:11

Jacob Dam