Finalization in Go: Default Objects and Pitfalls
The Go runtime automatically finalizes specific objects when they are garbage collected. This built-in mechanism can lead to potential pitfalls if not thoroughly understood.
Default Finalized Objects:
Pitfalls of Default Finalization:
When os.File is finalized, it invokes the operating system to close its file descriptor. However, if this file descriptor is shared with another os.File object created using os.NewFile(fd int, name string) *File, finalizing either object will corrupt the other.
For instance, consider the following code:
package main import ( "fmt" "os" "runtime" ) func open() { os.NewFile(1, "stdout") } func main() { open() // Force finalization of unreachable objects _ = make([]byte, 1e7) runtime.GC() _, err := fmt.Println("some text") // Print something via os.Stdout if err != nil { fmt.Fprintln(os.Stderr, "could not print the text") } }
This code would fail with the following error, due to the shared file descriptor:
could not print the text
The above is the detailed content of How Does Go's Automatic Object Finalization Work, and What are its Potential Pitfalls?. For more information, please follow other related articles on the PHP Chinese website!