Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: sub DESTROY: Strange ordering of object destruction

by Corion (Patriarch)
on Mar 03, 2011 at 09:55 UTC ( [id://891185]=note: print w/replies, xml ) Need Help??


in reply to sub DESTROY: Strange ordering of object destruction (SOLVED)

Object destruction order is not respected anymore once Global Destruction sets in.

Global destruction happens after your main script "falls off the end" (or calls exit) and all END blocks have executed.

A way I've used to better localize the memory cycle that keeps objects alive until Global Destruction is to explicitly release the "master object" at the last (executed) line of the program:

undef $object;

If that works and everything gets released properly, this means you have a simple cycle and $object is kept alive somehow. There are some cases of closures that keep your lexical variables alive beyond the main program. One especially nasty case (for me) is:

my $object; sub frobnitz { $object->do_frobnitz; }; print "Done";

... but also, creating and handing around other closures might create problems, especially if these closures are kept alive somewhere:

sub make_frobnitz { my $frobnitz; my $obj = $_[0]; # $object $frobnitz = sub { $obj->frobnitz; }; return $frobnitz # $frobnitz might stay alive forever, keeping $ob +j alive };

Careful use of Scalar::Util::weaken or careful undeffing of $object within (one-shot) closures might help to locate and eliminate the problem.

If all else fails, defensive programming in the destructors also helps (taken from MozRepl::RemoteObject, which has this problem):

sub DESTROY { my $self = shift; local $@; ... my $id = $self->__id(); return unless $self->__id(); my $release_action; if ($release_action = ($self->__release_action || '')) { ... }; if ($self->bridge) { # not always there during global destruction my $rn = $self->bridge->name; if ($rn) { # not always there during global destruction ... } else { # warn "Repl '$rn' has gone away already"; }; 1 } else { if ($MozRepl::RemoteObject::WARN_ON_LEAKS) { warn "Can't release JS part of object $self / $id ($releas +e_action)"; }; }; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://891185]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (3)
As of 2024-03-29 07:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found