Skip to content

Commit 396e90b

Browse files
committed
RWMutex
1 parent ed1beb8 commit 396e90b

File tree

1 file changed

+6
-4
lines changed

1 file changed

+6
-4
lines changed

loader.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ func New(fn LoadFunc, ttl time.Duration, cache Cache) *Loader {
4040
}
4141
}
4242

43+
// SetErrorTTL how long it takes for this Loader to cache error
44+
// and refetch again
4345
func (l *Loader) SetErrorTTL(ttl time.Duration) {
4446
l.errTtl = ttl
4547
}
@@ -54,8 +56,8 @@ func (l *Loader) Get(key interface{}) (interface{}, error) {
5456
l.mutex.Unlock()
5557

5658
item := cached.(*cacheItem)
57-
item.mutex.Lock()
58-
defer item.mutex.Unlock()
59+
item.mutex.RLock()
60+
defer item.mutex.RUnlock()
5961

6062
// if the item is expired and it's not doing refetch
6163
if item.expire.Before(time.Now()) && atomic.CompareAndSwapInt32(&item.isFetching, 0, 1) {
@@ -64,7 +66,7 @@ func (l *Loader) Get(key interface{}) (interface{}, error) {
6466
return item.value, item.err
6567
}
6668

67-
item := &cacheItem{isFetching: 0, mutex: sync.Mutex{}}
69+
item := &cacheItem{isFetching: 0, mutex: sync.RWMutex{}}
6870
item.mutex.Lock()
6971
defer item.mutex.Unlock()
7072

@@ -105,7 +107,7 @@ type cacheItem struct {
105107
err error
106108
expire time.Time
107109

108-
mutex sync.Mutex
110+
mutex sync.RWMutex
109111
isFetching int32
110112
}
111113

0 commit comments

Comments
 (0)