Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Cleanup / Finalization

It is possible to run special code when an actor is about to be garbage collected. This is mainly for actors that manage outside resources and need a best-effort final step when they become unreachable.

Define an actor action called __cleanup__ and the runtime will schedule it when garbage collection notices that the actor is no longer reachable. There is no hard guarantee when __cleanup__ will run, and it can take more than one collection round before all finalizers are handled.

Cleanup hooks are intentionally weakly timed. They are useful for best-effort resource cleanup at the boundary to the outside world, but they are not a substitute for explicit shutdown protocols when a system needs deterministic release or ordering.

Source:

actor Foo():
    action def __cleanup__():
        print("Cleaning up after myself...")

actor main(env):
    for i in range(20):
        Foo()

    a = 1
    for i in range(99999):
        a += i

    def _stop():
        env.exit(0)
    after 0.1: _stop()

Output:

Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...
Cleaning up after myself...