Skip to content

Commit 1f03d0f

Browse files
committed
Implement BadgerDB garbage collector with mutex
1 parent 1ca2ddf commit 1f03d0f

File tree

2 files changed

+17
-23
lines changed

2 files changed

+17
-23
lines changed

internal/database/badger_gc.go

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package database
1717

1818
import (
1919
"errors"
20+
"sync"
2021
"time"
2122

2223
"github.com/dgraph-io/badger/v3"
@@ -31,8 +32,8 @@ type BadgerGarbageCollector struct {
3132
db *badger.DB
3233
log *logr.Logger
3334
// flow control
34-
timer *time.Timer
35-
stop chan struct{}
35+
timer *time.Timer
36+
running sync.Mutex
3637
}
3738

3839
// NewBadgerGarbageCollector creates and returns a new
@@ -43,40 +44,33 @@ func NewBadgerGarbageCollector(db *badger.DB, interval time.Duration, log *logr.
4344

4445
db: db,
4546
log: log,
46-
47-
timer: time.NewTimer(interval),
48-
stop: make(chan struct{}),
4947
}
5048
}
5149

52-
// Run repeatedly runs the BadgerDB garbage collector with a delay inbetween
50+
// Start repeatedly runs the BadgerDB garbage collector with a delay inbetween
5351
// runs.
5452
//
55-
// This is a blocking operation, so it should be run as a separate goroutine.
53+
// This is a non-blocking operation.
5654
// To stop the garbage collector, call Stop().
57-
func (gc *BadgerGarbageCollector) Run() {
55+
func (gc *BadgerGarbageCollector) Start() {
5856
gc.log.Info("Starting Badger GC")
59-
for {
60-
select {
61-
case <-gc.timer.C:
62-
gc.discardValueLogFiles()
63-
gc.timer.Reset(gc.Interval)
64-
case <-gc.stop:
65-
gc.timer.Stop()
66-
gc.log.Info("Stopped Badger GC")
67-
gc.stop <- struct{}{}
68-
return
69-
}
70-
}
57+
gc.timer = time.AfterFunc(gc.Interval, func() {
58+
gc.running.Lock()
59+
gc.discardValueLogFiles()
60+
gc.running.Unlock()
61+
gc.timer.Reset(gc.Interval)
62+
})
7163
}
7264

7365
// Stop blocks until the garbage collector has been stopped.
7466
//
7567
// To avoid GC Errors, call Stop() before closing the database.
7668
func (gc *BadgerGarbageCollector) Stop() {
7769
gc.log.Info("Sending stop to Badger GC")
78-
gc.stop <- struct{}{}
79-
<-gc.stop
70+
gc.timer.Stop()
71+
gc.running.Lock()
72+
gc.running.Unlock()
73+
gc.log.Info("Stopped Badger GC")
8074
}
8175

8276
// upper bound for loop

main.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ func main() {
136136
defer badgerDB.Close()
137137

138138
badgerGC := database.NewBadgerGarbageCollector(badgerDB, 1*time.Minute, &gcLog)
139-
go badgerGC.Run()
139+
badgerGC.Start()
140140
defer badgerGC.Stop()
141141

142142
db := database.NewBadgerDatabase(badgerDB)

0 commit comments

Comments
 (0)