-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgc_unclosed.go
52 lines (42 loc) · 1.16 KB
/
gc_unclosed.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package ex
import (
"fmt"
"os"
"runtime"
)
var onGarbageCollectUnclosed = func(err error) {
fmt.Fprintln(os.Stderr, err)
}
// OnGarbageCollectUnclosed changes what happens when a Terminator
// gets garbage collected without the Close method having been called.
//
// The default behaviour is to write an error message to stderr.
// Use this for example if you prefer to panic or pass it to your log
// system instead of stderr.
func OnGarbageCollectUnclosed(handler func(error)) {
if handler == nil {
panic("Cannot set a nil garbage collect unclosed handler")
}
onGarbageCollectUnclosed = handler
}
type gcUnclosedDetector struct {
description string
isClosed bool
}
func newGCUnclosedDetector(description string) *gcUnclosedDetector {
detector := &gcUnclosedDetector{
description: description,
isClosed: false,
}
runtime.SetFinalizer(detector, (*gcUnclosedDetector).finalizer)
return detector
}
func (detector *gcUnclosedDetector) finalizer() {
if detector.isClosed {
return
}
onGarbageCollectUnclosed(fmt.Errorf(
"The Close method of the terminator containing a %s was never called before being garbage collected.",
detector.description,
))
}