Skip to content

proposal: runtime: introduce convention of using SetFinalizer to help detect resource leaks #24696

@akavel

Description

@akavel

Rationale

Inspired by a recent comment on r/golang by BowsersaurusRex:

In C# I'll often use finalizers to track bugs in which an object was GC'd but Close() was never called.

and the post by @crawshaw which led to it, I started to think that maybe the idea quoted above (to use finalizers to help detect resource leaks) could be promoted into a "good practice", with some support in the standard library. It's just an idea, and quick googling didn't lead me to any previous discussion of a similar proposal (though see Related Work below), so I thought to open an issue to start a discussion and explore whether it could be seen as reasonable and advisable.

Proposal

As a quick first draft, I propose the following new variable is added in package runtime:

package runtime

// Leaks is a channel where resource leaks detected by packages are sent
// on best-effort basis. Errors received from this channel can help pinpoint
// resource leaks such as missing File.Close calls.
//
// TODO: example code showing SetFinalizer usage pattern
var Leaks = make(chan error)

and then for example os.File's finalizer is changed from current .close call:

runtime.SetFinalizer(f.file, (*file).close)

to something like below:

runtime.SetFinalizer(f.file, (*file).leak)

where leak could be implemented as:

func (file *file) leak() {
    select {
    case runtime.Leaks <- errors.New(file.name + ": missing Close):
    default:
    }
    file.close()
}

(Discussion thread on golang-nuts)

Related Work

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions