nitg & lib: intro `Finalizable` to be called when an object is freed
[nit.git] / lib / standard / gc.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
9 # another product.
10
11 # Access to the Nit internal garbage collection mechanism
12 module gc
13
14 import kernel
15
16 redef class Sys
17 # Initiate a garbage collection
18 fun force_garbage_collection is intern
19 end
20
21 # An object needing finalization
22 #
23 # Sub-classes of `Finalizable` must no have cycles, or else they will not be
24 # liberated. For this reason, it is recommended to sub-class `Finalizable`
25 # only on simple objects directly managing a limited resource. This use case
26 # is common when wrapping an extern instance with a standard object.
27 class Finalizable
28
29 # Liberate any resources held by `self` before the memory holding `self` is freed
30 #
31 # This method is invoked by the GC during a garbage collection when `self`
32 # is no longer referenced. It can also be called by the user. Its implementation
33 # must be planned accordingly and ensure that it may be invoked more than once.
34 #
35 # The object are finialized in a topological order, it is safe for this method
36 # to use attributes of this instances.
37 fun finalize do end
38 end