The function runtime.SetFinalizer(x, f interface{})
sets the finalizer associated with x
to f
.
What kind of objects are finalized by default?
What are some of the unintended pitfalls caused by having those objects finalized by default?
The function runtime.SetFinalizer(x, f interface{})
sets the finalizer associated with x
to f
.
What kind of objects are finalized by default?
What are some of the unintended pitfalls caused by having those objects finalized by default?
Just jump into the os.NewFile's source code:
The following objects are finalized by default:
os.File: The file is automatically closed when the object is garbage collected.
os.Process: Finalization will release any resources associated with the process. On Unix, this is a no-operation. On Windows, it closes the handle associated with the process.
On Windows, it appears that package
net
can automatically close a network connection.The Go standard library is not setting a finalizer on object kinds other than the ones mentioned above.
There seems to be only one potential issue that may cause problems in actual programs: When an
os.File
is finalized, it will make a call to the OS to close the file descriptor. In case theos.File
has been created by calling functionos.NewFile(fd int, name string) *File
and the file descriptor is also used by another (different)os.File
, then garbage collecting either one of the file objects will render the other file object unusable. For example:prints:
"What kind of objects are finalized by default?"
Nothing in Go is IMO finalized by default.
"What are some of the unintended pitfalls caused by having those objects finalized by default?"
As per above: none.