Documentation
¶
Overview ¶
Package resource provides facilities for tracking resource lifetimes.
In Go, it is common for resources to be allocated by the NewXXX function and released by the Close or similar method. This package allows tracking of such resources with custom pprof profiles and ensures that this method is actually called.
To use it, first create a Handle with the NewHandle function and store it in a resource being tracked, typically as a non-embedded pointer field of a struct. Then, call Track with both the resource and handler pointer. It is recommended to do all of that in the NewXXX function.
Resource's Close method implementation should call Untrack. If the resource becomes unreachable and is garbage-collected without this method being called, the runtime would panic with a stack trace showing the Track call.
Additionally, currently traced resources are shown in custom pprof profiles named after resource types.
Example ¶
// The default cleanup function panics with a stack trace of the Track call.
cleanup = func(h *Handle) {
fmt.Printf("%s wasn't released!", h.typ)
}
res := &Resource{
h: NewHandle(),
}
Track(res, res.h)
runtime.GC()
runtime.GC()
Output: resource.Resource wasn't released!
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
Types ¶
type Handle ¶
type Handle struct {
// contains filtered or unexported fields
}
Handle holds the runtime.Cleanup to stop resource lifetime tracking.
It must be created with NewHandle. It must be passed to Track and Untrack together with the resource. Just creating and storing a handle does not enable tracking.
It must not be used for tracking multiple resources.
It is recommended to store it as non-embedded pointer field of a resource struct being tracked.