chore: Adjust cache lock usage

This commit is contained in:
giveup 2025-01-02 17:33:55 +08:00
parent 1c5f4a3ab1
commit 5b43cabc49
2 changed files with 12 additions and 12 deletions

View file

@ -26,7 +26,7 @@ type ARC[K comparable, V any] struct {
b1 *list.List[*entry[K, V]]
t2 *list.List[*entry[K, V]]
b2 *list.List[*entry[K, V]]
mutex sync.Mutex
mutex sync.RWMutex
len int
cache map[K]*entry[K, V]
}
@ -100,8 +100,8 @@ func (a *ARC[K, V]) setWithExpire(key K, value V, expires time.Time) {
// Get retrieves a previously via Set inserted entry.
// This optimizes future access to this entry (side effect).
func (a *ARC[K, V]) Get(key K) (value V, ok bool) {
a.mutex.Lock()
defer a.mutex.Unlock()
a.mutex.RLock()
defer a.mutex.RUnlock()
ent, ok := a.get(key)
if !ok {
@ -124,8 +124,8 @@ func (a *ARC[K, V]) get(key K) (e *entry[K, V], ok bool) {
// and a bool set to true if the key was found.
// This method will NOT update the expires.
func (a *ARC[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
a.mutex.Lock()
defer a.mutex.Unlock()
a.mutex.RLock()
defer a.mutex.RUnlock()
ent, ok := a.get(key)
if !ok {

View file

@ -58,7 +58,7 @@ func WithStale[K comparable, V any](stale bool) Option[K, V] {
type LruCache[K comparable, V any] struct {
maxAge int64
maxSize int
mu sync.Mutex
mu sync.RWMutex
cache map[K]*list.Element[*entry[K, V]]
lru *list.List[*entry[K, V]] // Front is least-recent
updateAgeOnGet bool
@ -89,8 +89,8 @@ func (c *LruCache[K, V]) Clear() {
// Get returns any representation of a cached response and a bool
// set to true if the key was found.
func (c *LruCache[K, V]) Get(key K) (V, bool) {
c.mu.Lock()
defer c.mu.Unlock()
c.mu.RLock()
defer c.mu.RUnlock()
el := c.get(key)
if el == nil {
@ -121,8 +121,8 @@ func (c *LruCache[K, V]) GetOrStore(key K, constructor func() V) (V, bool) {
// and a bool set to true if the key was found.
// This method will NOT check the maxAge of element and will NOT update the expires.
func (c *LruCache[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
c.mu.Lock()
defer c.mu.Unlock()
c.mu.RLock()
defer c.mu.RUnlock()
el := c.get(key)
if el == nil {
@ -134,8 +134,8 @@ func (c *LruCache[K, V]) GetWithExpire(key K) (V, time.Time, bool) {
// Exist returns if key exist in cache but not put item to the head of linked list
func (c *LruCache[K, V]) Exist(key K) bool {
c.mu.Lock()
defer c.mu.Unlock()
c.mu.RLock()
defer c.mu.RUnlock()
_, ok := c.cache[key]
return ok