Merge: doc: fixed some typos and other misc. corrections
[nit.git] / lib / core / 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 # It is recommended to sub-class `Finalizable` only on
24 # simple objects directly managing a limited resource. This use case
25 # is common when wrapping an extern instance with a standard object.
26 class Finalizable
27
28 # Liberate any resources held by `self` before the memory holding `self` is freed
29 #
30 # This method is invoked by the GC during a garbage collection when `self`
31 # is no longer referenced. It can also be called by the user. Its implementation
32 # must be planned accordingly and ensure that it may be invoked more than once.
33 #
34 # The object are not finialized in a topological order, it is safe for this method
35 # to use attributes of this instances, unless theses attributes are finalizable as well
36 # because they may have been finalized already.
37 fun finalize do end
38 end
39
40 # An object to be finalized only once
41 #
42 # This is an utility sub-class to `Finalizable` which ensures that `finalized_once`
43 # is called only once per instance. User classes implementing `FinalizableOnce`
44 # shoud specialize `finalize_once` and _not_ `finalize`. When manipulating the user
45 # class, only `finalize` should be called as it protects `finalize_once`.
46 class FinalizableOnce
47 super Finalizable
48
49 # Has `self` been finalized? (either by the GC or an explicit call to `finalize`)
50 var finalized = false
51
52 redef fun finalize
53 do
54 if finalized then return
55
56 finalize_once
57 finalized = true
58 end
59
60 # Real finalization method of `FinalizableOnce`, will be called only once
61 #
62 # See: `Finalizable::finalize` for restrictions on finalizer methods.
63 protected fun finalize_once do end
64 end