From 2091bf94931bddcf23b196fc8fe108ebd7ec1648 Mon Sep 17 00:00:00 2001 From: Peter Zhu Date: Mon, 24 Jul 2023 10:48:39 -0400 Subject: Expose stats about weak references [Feature #19783] This commit adds stats about weak references to `GC.latest_gc_info`. It adds the following two keys: - `weak_references_count`: number of weak references registered during the last GC. - `retained_weak_references_count`: number of weak references that survived the last GC. --- test/ruby/test_gc.rb | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) (limited to 'test/ruby') diff --git a/test/ruby/test_gc.rb b/test/ruby/test_gc.rb index 8d77e65bbe..bfcfbbb72f 100644 --- a/test/ruby/test_gc.rb +++ b/test/ruby/test_gc.rb @@ -286,6 +286,54 @@ class TestGc < Test::Unit::TestCase assert_not_nil(major_by) end + def test_latest_gc_info_weak_references_count + assert_separately([], __FILE__, __LINE__, <<~RUBY) + count = 10_000 + # Some weak references may be created, so allow some margin of error + error_tolerance = 100 + + # Run full GC to clear out weak references + GC.start + # Run full GC again to collect stats about weak references + GC.start + + before_weak_references_count = GC.latest_gc_info(:weak_references_count) + before_retained_weak_references_count = GC.latest_gc_info(:retained_weak_references_count) + + # Create some objects and place it in a WeakMap + wmap = ObjectSpace::WeakMap.new + ary = Array.new(count) + count.times do |i| + obj = Object.new + ary[i] = obj + wmap[obj] = nil + end + + # Run full GC to collect stats about weak references + GC.start + + assert_operator(GC.latest_gc_info(:weak_references_count), :>=, before_weak_references_count + count - error_tolerance) + assert_operator(GC.latest_gc_info(:retained_weak_references_count), :>=, before_retained_weak_references_count + count - error_tolerance) + assert_operator(GC.latest_gc_info(:retained_weak_references_count), :<=, GC.latest_gc_info(:weak_references_count)) + + before_weak_references_count = GC.latest_gc_info(:weak_references_count) + before_retained_weak_references_count = GC.latest_gc_info(:retained_weak_references_count) + + ary = nil + + # Free ary, which should empty out the wmap + GC.start + # Run full GC again to collect stats about weak references + GC.start + + assert_equal(0, wmap.size) + + assert_operator(GC.latest_gc_info(:weak_references_count), :<=, before_weak_references_count - count + error_tolerance) + assert_operator(GC.latest_gc_info(:retained_weak_references_count), :<=, before_retained_weak_references_count - count + error_tolerance) + assert_operator(GC.latest_gc_info(:retained_weak_references_count), :<=, GC.latest_gc_info(:weak_references_count)) + RUBY + end + def test_stress_compile_send assert_in_out_err(%w[--disable-gems], <<-EOS, [], [], "") GC.stress = true -- cgit v1.2.3