Skip to content

Commit eb11349

Browse files
authored
refactor(blockdb): use atomic.Bool for cacheDB closed state (#4521)
1 parent 3b08d61 commit eb11349

File tree

1 file changed

+8
-23
lines changed

1 file changed

+8
-23
lines changed

x/blockdb/cache_db.go

Lines changed: 8 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ package blockdb
55

66
import (
77
"slices"
8-
"sync"
8+
"sync/atomic"
99

1010
"go.uber.org/zap"
1111

@@ -22,11 +22,9 @@ var _ database.HeightIndex = (*cacheDB)(nil)
2222
// the cache and database contain different values. This limitation is acceptable
2323
// because concurrent writes to the same height are not an intended use case.
2424
type cacheDB struct {
25-
db *Database
26-
cache *lru.Cache[BlockHeight, BlockData]
27-
28-
closeMu sync.RWMutex
29-
closed bool
25+
db *Database
26+
cache *lru.Cache[BlockHeight, BlockData]
27+
closed atomic.Bool
3028
}
3129

3230
func newCacheDB(db *Database, size uint16) *cacheDB {
@@ -37,10 +35,7 @@ func newCacheDB(db *Database, size uint16) *cacheDB {
3735
}
3836

3937
func (c *cacheDB) Get(height BlockHeight) (BlockData, error) {
40-
c.closeMu.RLock()
41-
defer c.closeMu.RUnlock()
42-
43-
if c.closed {
38+
if c.closed.Load() {
4439
c.db.log.Error("Failed Get: database closed", zap.Uint64("height", height))
4540
return nil, database.ErrClosed
4641
}
@@ -57,10 +52,7 @@ func (c *cacheDB) Get(height BlockHeight) (BlockData, error) {
5752
}
5853

5954
func (c *cacheDB) Put(height BlockHeight, data BlockData) error {
60-
c.closeMu.RLock()
61-
defer c.closeMu.RUnlock()
62-
63-
if c.closed {
55+
if c.closed.Load() {
6456
c.db.log.Error("Failed Put: database closed", zap.Uint64("height", height))
6557
return database.ErrClosed
6658
}
@@ -74,10 +66,7 @@ func (c *cacheDB) Put(height BlockHeight, data BlockData) error {
7466
}
7567

7668
func (c *cacheDB) Has(height BlockHeight) (bool, error) {
77-
c.closeMu.RLock()
78-
defer c.closeMu.RUnlock()
79-
80-
if c.closed {
69+
if c.closed.Load() {
8170
c.db.log.Error("Failed Has: database closed", zap.Uint64("height", height))
8271
return false, database.ErrClosed
8372
}
@@ -89,13 +78,9 @@ func (c *cacheDB) Has(height BlockHeight) (bool, error) {
8978
}
9079

9180
func (c *cacheDB) Close() error {
92-
c.closeMu.Lock()
93-
defer c.closeMu.Unlock()
94-
95-
if c.closed {
81+
if !c.closed.CompareAndSwap(false, true) {
9682
return database.ErrClosed
9783
}
98-
c.closed = true
9984
c.cache.Flush()
10085
return c.db.Close()
10186
}

0 commit comments

Comments
 (0)