Golang's runtime. Setfinaliz

Source: Internet
Author: User
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.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.