Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

finalizer

raku

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.

like image 449
brian d foy Avatar asked Jun 13 '18 00:06

brian d foy


People also ask

What is Perl 6 good for?

The Perl 6 solution is to allow multi-method dispatch, which not only removes conceptual complexity (at least, MMD is easier to explain than tie ) but also provides the possibility of a cleaner implementation.

What is Perl 6 called?

Raku is a member of the Perl family of programming languages. Formerly known as Perl 6, it was renamed in October 2019.

When did Perl 6 come out?

Perl 6 First Official Release. Released on December 24, 2015, Perl 6 Version 1.0 is also Perl 6.


1 Answers

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.

like image 109
Elizabeth Mattijsen Avatar answered Sep 28 '22 01:09

Elizabeth Mattijsen