Does Perl 6 automatically call any special methods when it cleans up an object?
Asked Answered
A

1

14

I thought that Rakudo got finalizer support several years ago but I couldn't find the documentation for it (maybe it goes in Classes and Objects). Listing all the methods in a class didn't seem like the thing I was looking for.

class Butterfly {
    method DESTROY { put "Destroyed" }
    # submethod DESTROY { put "Destroyed" }
    }
{
Butterfly.new;
}

Maybe the problem is #127243: [RFC] DESTROY is not called on interpreter exit

Ah, and marked as "to do" in roast/S12-construction/destruction.t.

Aquitaine answered 13/6, 2018 at 0:19 Comment(1)
Jonathan Worthington gives a detailed answer in the GitHub issue motivated by this question: github.com/perl6/doc/issues/2097#issuecomment-396881299Aquitaine
T
14

There is no reliable object finalization in Perl 6. There is support for DESTROY, but it will only get called when the object is actually garbage collected. Garbage collection does not happen on global shutdown, but when it is needed (from whatever heuristics it decides that).

The following code shows that when objects get garbage collected, they call DESTROY:

my int $destroyed;
class A {
    method DESTROY { ++$seen }
}
A.new for ^50000;
say "DESTROY called $destroyed times";

Which will typically output something like: "DESTROY called 31095 times".

If you want reliable destruction, you could use LEAVE phasers, or the will leave trait:

my $dbh = DBI.connect(....);
LEAVE $dbh.disconnect;

or shorter:

my $foo will leave { say "left with $_" } = 42;
# left with 42

One should realize that reference counting, which allows for reliable destruction, has its problems (circular references, so you need weak references, unsharing of shared memory because it needs to update counters, XS code getting it wrong, etc. etc.). In a purely threaded environment, this becomes untenable, because you would need to do all ref counting atomically (either by using hardware features, or by locking). Which, apart from generally slowing down things, opens up a whole new pool of possible deadlocks.

Testee answered 13/6, 2018 at 9:8 Comment(2)
Hi Liz. "There is no reliable object finalization in Perl 6." But there is with your FINALIZER module, right?Malonylurea
In principle yes, but I don't know of any people who actually tried to use it but me, so it may still be a little rough around the edges.Testee

© 2022 - 2024 — McMap. All rights reserved.