This is a creation in Article, where the information may have evolved or changed.
In the actual programming, we all want to execute a method when each object is disposed, to perform some count, release, or specific requirements within the method, which used to call a specific method before the object pointer is nil, Golang provides runtime. The Setfinalizer function, when the GC is ready to release the object, will callback the method specified by the function, which is very convenient and efficient.
It is noteworthy, however, that the "loop ⽤" of the pointer is added to the runtime. Setfinalizer can cause a memory leak.
typeDatastruct{d [1024x768* -]byteo *data} func test() {varA, b Data a.o = &b b.o = &a runtime. Setfinalizer (&a, func(d *data) {FMT. Printf ("a%p final.\n", d)}) runtime. Setfinalizer (&b, func(d *data) {FMT. Printf ("b%p final.\n", d)})} func main() { for{test () time. Sleep (Time.millisecond)}}
Output:
$ Go build-gcflags"-n-l"&& godebug="Gctrace=1"./TESTGC11 (1):2+0+0Ms104-104MB1127-1127(1180- -) OBJECTSGC12 (1):4+0+0Ms208-208MB2151-2151(2226- the) Objectsgc13 (1):8+0+1Ms416-416MB4198-4198(4307-109) objects
The garbage collector can correctly handle the "pointer loop ⽤", but the ⽆ method determines the Finalizer dependency order, and ⽆ the ⽤finalizer function, which causes the target object ⽆ method to become unreachable, and the ⽤ memory ⽆ method is recycled.