From: Peter Zotov Date: 2012-09-18T02:49:28+09:00 Subject: Re: Finalizer in the GC Tridib Bandopadhyay писал 17.09.2012 19:56: > Hello > > Why does GC uses finalizer in the sweep phase? Also what is the > final_list? > > Thanks > > Tridib Judging from my telepathic abilities, you are talking about Ruby MRI 1.9.x. GC invokes finalizers in the sweep phase because before the end of the mark phase you don't know which objects will remain alive and which will be collected. Ruby uses a (somewhat contrived) packed format for storing objects in memory. The basis of it is the struct RVALUE, defined here: http://rxr.whitequark.org/mri/source/gc.c#146 The first VALUE-sized field in any Ruby object is always the flags; these flags signify the type of the object and explain how to decode the following data. If flags == 0, then the object is already freed and the second VALUE-sized field points to the next freed object, thus forming a singly linked list. It also happens that all of the non-RBasic types extend RBasic, and the as.free.next field is located at the same place as RBasic's klass field: http://rxr.whitequark.org/mri/source/include/ruby/ruby.h#621 Finalizers are actually run as part of the rb_objspace_call_finalizer routine: http://rxr.whitequark.org/mri/source/gc.c#1466 This routine effectively references two different chains of finalizable objects. First chain, called deferred_final_list is a global one (it's expanded to a field in the objspace global object), and the second is a local variable final_list. They have the same semantics, through. The first chain is collected via chain_finalized_object (#1427) and contains plain Ruby objects with finalizers, and the second one is collected at #1518-1529. ... There could be a nice explanation, but I caught myself on the fact that I don't understand why does MRI's GC have two separate finalizer list, or why does it repeatedly try to finalize all objects in hopes that the finalizable list will shrink to zero elements, or why does it "force-finalize" the rest of objects anyway after rebuilding the list as a hash table. I'm probably too stupid, or my telepathy skill is not good enough, or the comment /* XXX: this loop will make no sense */ precisely describes the situation and all of that doesn't make sense. -- WBR, Peter Zotov.