@@ -5,7 +5,7 @@ package blockdb
55
66import (
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.
2424type 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
3230func newCacheDB (db * Database , size uint16 ) * cacheDB {
@@ -37,10 +35,7 @@ func newCacheDB(db *Database, size uint16) *cacheDB {
3735}
3836
3937func (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
5954func (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
7668func (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
9180func (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