rcrowley / go-metrics

Go port of Coda Hale's Metrics library
Other
3.43k stars 493 forks source link

Use runtime.SetFinalizer on registration to avoid the need to Unregister meters or timers #280

Open AdamSLevy opened 3 years ago

AdamSLevy commented 3 years ago

Requiring users to Unregister metrics that they allow to be garbage collected is error prone and can then lead to GC leaks. However it is possible to leverage the garbage collector to perform final cleanup steps on an object. I propose that upon registration, a metric, counter, timer or gauge has an appropriate finalizer function set on it so that any cleanup operations can be performed.

This will likely require an additional nested layer of indirection so that the actual data that is saved in the registry does not prevent garbage collection on the outer object passed back to the user.

See https://golang.org/pkg/runtime/#SetFinalizer

I can come back with an example in code this weekend if this isn't clear enough.