Last active
August 29, 2015 14:08
-
-
Save zentourist/d070f823ba59ff8c99f5 to your computer and use it in GitHub Desktop.
Playing with the Ruby Garbage Collector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require "objspace" | |
| class TestWithFinalizer | |
| def self.finalizer | |
| proc {|o_id| puts "Collected #{o_id}"} | |
| end | |
| def test | |
| 3.times.each_with_object(mark []) {|i,a| | |
| a << mark({ i => i }) | |
| } | |
| end | |
| def mark(x) | |
| ObjectSpace.define_finalizer(x, TestWithFinalizer.finalizer) | |
| puts "Marked #{x.object_id} - #{x.class}" | |
| x | |
| end | |
| end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This is the confusing session. It consistently never collects the last reference until after I `exit`. | |
| # I can also successfully get the object from the object_id via `ObjectSpace._id2ref()` | |
| t = TestWithFinalizer.new | |
| o = t.test; nil # follow with 'nil' or Pry stores the output ref | |
| # Marked 18869680 - Array | |
| # Marked 18869420 - Hash | |
| # Marked 18869220 - Hash | |
| # Marked 18869020 - Hash | |
| o = nil | |
| ObjectSpace.garbage_collect | |
| # Collected 18869680 | |
| # Collected 18869420 | |
| # Collected 18869220 | |
| exit | |
| # Collected 18869020 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This is the way I would expect it to behave. | |
| t = TestWithFinalizer.new | |
| o1 = t.test; nil | |
| # Marked 22159300 | |
| # Marked 22159280 | |
| # Marked 22159260 | |
| # Marked 22159240 | |
| o2 = t.test; nil | |
| # Marked 22268960 | |
| # Marked 22268940 | |
| # Marked 22268920 | |
| # Marked 22268900 | |
| o1 = nil | |
| ObjectSpace.garbage_collect | |
| # Collected 22159300 | |
| # Collected 22159280 | |
| # Collected 22159260 | |
| # Collected 22159240 | |
| o2 = nil | |
| ObjectSpace.garbage_collect | |
| # Collected 22268960 | |
| # Collected 22268940 | |
| # Collected 22268920 | |
| # Collected 22268900 | |
| exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment