Using runtime.SetFinalizer as rescue from forgotten close

My colleague is using runtime.SetFinalizer for resource which need to be closed. Finalizer would simply close resource, and his argument is that it will prevent errors in case code which is using library won’t close resource implicitly.
Finalizer might have log of even panic to remind user he forgot to close resource.
What is your opinion about such use of SetFinalizer?

PS. Here is example from go code: https://golang.org/src/os/file_unix.go#L55

I see two possible issues with this approach:

  1. Getting used to depending on the finalizer fixing all forgotten resource cleanups might lead to sloppy programming style.

  2. The finalizer comes with a set of non-guarantees:

There is no guarantee that finalizers will run before a program exits, so typically they are useful only for releasing non-memory resources associated with an object during a long-running program. For example, an os.File object could use a finalizer to close the associated operating system file descriptor when a program discards an os.File without calling Close, but it would be a mistake to depend on a finalizer to flush an in-memory I/O buffer such as a bufio.Writer, because the buffer would not be flushed at program exit.

It is not guaranteed that a finalizer will run if the size of *x is zero bytes.

It is not guaranteed that a finalizer will run for objects allocated in initializers for package-level variables. Such objects may be linker-allocated, not heap-allocated.

For me, these would be too many uncertainties in order to rely upon the finalizer.

Using finalizers as a debugging tool for reminding the developer on forgotten cleanups seems a good idea though.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.