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.