Skip to content

Commit 7293583

Browse files
committed
Resources allocation improvement.
1 parent dbd005b commit 7293583

File tree

1 file changed

+23
-18
lines changed

1 file changed

+23
-18
lines changed

cache/cache.go

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -11,31 +11,29 @@ type CacheEntry struct {
1111
}
1212

1313
type Cache struct {
14-
sync.Mutex
14+
sync.RWMutex
1515
entries map[string]CacheEntry
1616
globalTTL time.Duration
17-
ticker *time.Ticker
1817
}
1918

2019
func New(globalTTL time.Duration) *Cache {
2120
cache := &Cache{
2221
entries: make(map[string]CacheEntry),
2322
globalTTL: globalTTL,
24-
ticker: time.NewTicker(globalTTL / 2),
2523
}
2624

27-
// Start the cache.
28-
cache.Start()
25+
// Start the cache cleanup.
26+
go cache.cleanupRoutine(globalTTL)
2927
return cache
3028
}
3129

32-
func (c *Cache) Start() {
33-
go func() {
34-
for {
35-
<-c.ticker.C
36-
c.CleanExpiredEntries()
37-
}
38-
}()
30+
func (c *Cache) cleanupRoutine(globalTTL time.Duration) {
31+
ticker := time.NewTicker(globalTTL / 2)
32+
defer ticker.Stop()
33+
34+
for range ticker.C {
35+
c.CleanExpiredEntries()
36+
}
3937
}
4038

4139
func (c *Cache) Set(key string, value []byte, ttl time.Duration) {
@@ -55,8 +53,8 @@ func (c *Cache) Set(key string, value []byte, ttl time.Duration) {
5553
}
5654

5755
func (c *Cache) Get(key string) ([]byte, bool) {
58-
c.Lock()
59-
defer c.Unlock()
56+
c.RLock()
57+
defer c.RUnlock()
6058

6159
entry, ok := c.entries[key]
6260
if !ok || entry.ExpiresAt.Before(time.Now()) {
@@ -75,13 +73,20 @@ func (c *Cache) Delete(key string) {
7573

7674
func (c *Cache) CleanExpiredEntries() {
7775
now := time.Now()
76+
toDelete := make([]string, 0)
7877

79-
c.Lock()
80-
defer c.Unlock()
81-
78+
c.RLock()
8279
for key, entry := range c.entries {
8380
if entry.ExpiresAt.Before(now) {
84-
delete(c.entries, key)
81+
toDelete = append(toDelete, key)
8582
}
8683
}
84+
c.RUnlock()
85+
86+
// Separate the deletion to its own critical section to reduce lock contention.
87+
c.Lock()
88+
for _, key := range toDelete {
89+
delete(c.entries, key)
90+
}
91+
c.Unlock()
8792
}

0 commit comments

Comments
 (0)