Skip to content

Commit 1261d37

Browse files
committed
SetFinalizer to unmap files
This will help to clean up memory maps if the user failed to close the reader (within the limitations of finalizers, of course).
1 parent 6a69cca commit 1261d37

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

reader_other.go

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@
22

33
package maxminddb
44

5-
import "os"
5+
import (
6+
"os"
7+
"runtime"
8+
)
69

710
// Open takes a string path to a MaxMind DB file and returns a Reader
811
// structure or an error. The database file is opened using a memory map,
@@ -41,16 +44,18 @@ func Open(file string) (*Reader, error) {
4144
}
4245

4346
reader.hasMappedFile = true
47+
runtime.SetFinalizer(reader, (*Reader).Close)
4448
return reader, err
4549
}
4650

4751
// Close unmaps the database file from virtual memory and returns the
4852
// resources to the system. If called on a Reader opened using FromBytes
4953
// or Open on Google App Engine, this method does nothing.
50-
func (r *Reader) Close() (err error) {
51-
if r.hasMappedFile {
52-
err = munmap(r.buffer)
53-
r.hasMappedFile = false
54+
func (r *Reader) Close() error {
55+
if !r.hasMappedFile {
56+
return nil
5457
}
55-
return err
58+
runtime.SetFinalizer(r, nil)
59+
r.hasMappedFile = false
60+
return munmap(r.buffer)
5661
}

0 commit comments

Comments
 (0)