finalizers questions again

73 views
Skip to first unread message

tapi...@gmail.com

unread,
Mar 11, 2021, 9:42:49 AM3/11/21
to golang-nuts

The tailscale article https://tailscale.com/blog/netaddr-new-ip-type-for-go/ mentions a finalizer trick.

The SetFinalizer docs says the finalizer of an object is not guaranteed to be run. So the tailscale trick is valid, could I think that an object is not collected for sure if it has a finalizer and the finalizer has not run yet?




tapi...@gmail.com

unread,
Mar 11, 2021, 9:44:06 AM3/11/21
to golang-nuts
(sorry, missed a "if")
.... So if the tailscale trick is valid, could I think that an object is not collected for sure if it has a finalizer and the finalizer has not run yet?

Axel Wagner

unread,
Mar 11, 2021, 10:38:30 AM3/11/21
to tapi...@gmail.com, golang-nuts
ISTM that the docs imply this:

When the garbage collector finds an unreachable block with an associated finalizer, it clears the association and runs finalizer(obj) in a separate goroutine. This makes obj reachable again, but now without an associated finalizer. Assuming that SetFinalizer is not called again, the next time the garbage collector sees that obj is unreachable, it will free obj.

As long as we assume that the GC only collects unreachable data (which seems extremely plausible), it won't collect data that has a finalizer without running said finalizer.
I do think there are still some subtleties though. For example, if your finalizer does not actually *use* its parameter, the data might be considered unreachable (and collected) before you would consider the finalizer to "have run". e.g. if your finalizer is

func finalize(p *int) {
    fmt.Println("finalizer ran")
}

`p` might be collected before `finalizer ran` is printed. That is, your statement is only true if by "finalizer is run" you mean "finalizer is called", not "finalizer has returned".

At least as far as I understand it. Finalizers are subtle and I won't claim to actually understand them.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/8647fac5-5453-4598-870f-0048db3a454an%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages