finalize
If a class defines a finalize
method, when an instance of that class is garbage-collected that method will be invoked:
class Foo
def finalize
# Invoked when Foo is garbage-collected
# Use to release non-managed resources (ie. C libraries, structs)
end
end
Use this method to release resources allocated by external libraries that are not directly managed by Crystal garbage collector.
Examples of this can be found in IO::FileDescriptor#finalize
or OpenSSL::Digest#finalize
.
Notes:
-
The
finalize
method will only be invoked once the object has been fully initialized via theinitialize
method. If an exception is raised inside theinitialize
method,finalize
won't be invoked. If your class defines afinalize
method, be sure to catch any exceptions that might be raised in theinitialize
methods and free resources. -
Allocating any new object instances during garbage-collection might result in undefined behavior and most likely crashing your program.
To the extent possible under law, the persons who contributed to this workhave waived
all copyright and related or neighboring rights to this workby associating CC0 with it.
https://crystal-lang.org/reference/syntax_and_semantics/finalize.html