|No such thing as a small change|
Timing of garbage collectionby dd-b (Monk)
|on Jan 18, 2013 at 18:03 UTC||Need Help??|
dd-b has asked for the
wisdom of the Perl Monks concerning the following question:
As I understand it, object destruction happens in garbage collection, which is not guaranteed to happen at any particular time (before process termination). I must not count on actions in the destructor happening promptly when the last reference to an object goes away.
I've got a class that indexes members as they're created, and I need to keep that index clean because due to outside factors I don't control the same keys may come back fairly soon (outside forces prevent actual conflicts, but they do allow the same key to come up in close proximity in time).
So, I need to be sure that when I get rid of an object of this class, the cleanup happens immediately (before the next time I poll the outside forces for new work, which might give me new work with the same ID).
First, I put the cleanup in the destructor and just expected it to run. Then I realized that wasn't safe (due to the uncertain time of actual destruction), and changed to calling the destructor manually (I believe that's fairly safe, since this is a class used locally in a small controller program and I actually know when the objects aren't needed any more).
Then, after more thought, I added an instance method to take the current object out of the indexes, and just called that. (I also call it in the destructor; and because of that, it's become slightly more complicated and must handle the case where the object isn't currently in the indexes.)
(This maintaining an index is probably a recognized design pattern, but I'm not finding its name on a quick search. Sometimes factories do it, but this isn't a factory.)
So, just how undesirable is it to manually call object destructors? Is my current solution reasonably respectable? Or should I be using some completely different pattern, not trying to have the class index the class members for me or something? (Somebody has to index them.)