Re-use bucket objects in goleveldb
@@ -2,6 +2,7 @@ package db
import (
"path/filepath"
+ "sync"
"github.com/syndtr/goleveldb/leveldb"
"github.com/syndtr/goleveldb/leveldb/opt"
@@ -26,6 +27,7 @@ func NewGoLevelDBWithOpts(name string, dir string, o *opt.Options) (*GoLevelDB,
}
database := &GoLevelDB{
db: db,
+ buckets: make(map[BucketID]Bucket),
}
return database, nil
}
@@ -36,14 +38,25 @@ func NewGoLevelDBWithOpts(name string, dir string, o *opt.Options) (*GoLevelDB,
var _ Database = (*GoLevelDB)(nil)
type GoLevelDB struct {
+ lock sync.Mutex
db *leveldb.DB
+ buckets map[BucketID]Bucket
}
func (db *GoLevelDB) GetBucket(id BucketID) (Bucket, error) {
- return &goLevelBucket{
+ db.lock.Lock()
+ defer db.lock.Unlock()
+
+ if bk, ok := db.buckets[id]; ok {
+ return bk, nil
+ } else {
+ bk = &goLevelBucket{
id: id,
db: db.db,
- }, nil
+ }
+ db.buckets[id] = bk
+ return bk, nil
+ }
}
func (db *GoLevelDB) Close() error {
