On the use of finalizers for managing external resources
Tuesday, May 24th, 2011 21:05I have several times heard that one should not rely on finalizers (that is, code invoked after some object becomes garbage) to reclaim external resources (file descriptors, temporary files, etc.), on the grounds that there is no guarantee they will be promptly reclaimed and therefore one might run out.
Certainly for resources whose use has semantic significance to an outside system (e.g. a network connection or a locked file) or if there is a potential shortage of resources affecting other processes (e.g. free disk space), one should free them promptly whenever possible. (Finalizers are still important for error recovery unless you’re programming completely without nonlocal exits and extremely carefully, in which case you’re probably writing C and don’t have finalizers.)
But if the concern is for limited internal resources (most prominently, the limit on number of open file descriptors), and the process is entirely managed by the GC, would it not suffice to force a garbage collection and retry in the event that opening a file fails due to lack of file descriptors, just as if running out of memory while allocating memory?
No!
Date: 2011-05-25 12:10 (UTC)Not formally, no, because the GC may be aware that you are far from exhausting your currently available memory and not bother to do anything. Even worse, it might work for you on your machine because of the particular implementation of the garbage collection in whatever runtime you're using but your users may be using a different runtime which does GC differently.
Remember that "Garbage collection is simulating a computer with an infinite amount of memory": http://blogs.msdn.com/b/oldnewthing/archive/2010/08/09/10047586.aspx
(no subject)
Date: 2011-05-25 13:18 (UTC)Re: No!
Date: 2011-05-25 13:47 (UTC)That doesn't seem to be a large burden considering that doing this right also requires GC-and-retry code on every operation which allocates a file descriptor (or whatever).
Re: No!
Date: 2011-05-25 22:32 (UTC)Re: No!
Date: 2011-05-26 12:56 (UTC)(no subject)
Date: 2011-05-26 18:33 (UTC)Research topic :)
Date: 2011-06-13 09:40 (UTC)Re: Research topic :)
Date: 2011-06-13 15:35 (UTC)Your paper is about showing that a program will not run out of resources given arbitrary/malicious clients; my post is about allowing the programmer to manage resources less explicitly without losing reliability (that is, not introducing cases/orderings where the program fails despite having sufficient resources).