Skip to content

Commit

Permalink
Test cache finalizer
Browse files Browse the repository at this point in the history
  • Loading branch information
mgnsk committed Apr 29, 2024
1 parent d103027 commit f4d834c
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 7 deletions.
8 changes: 3 additions & 5 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,12 @@ type Cache[K comparable, V any] struct {

// New creates an empty cache.
func New[K comparable, V any](capacity int) *Cache[K, V] {
b := backend.NewBackend[K, V](capacity)

c := &Cache[K, V]{
backend: b,
backend: backend.NewBackend[K, V](capacity),
}

runtime.SetFinalizer(c, func(any) {
b.Close()
runtime.SetFinalizer(c, func(c *Cache[K, V]) {
c.backend.Close()
})

return c
Expand Down
24 changes: 24 additions & 0 deletions cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package evcache_test

import (
"fmt"
"runtime"
"testing"
"time"

Expand Down Expand Up @@ -225,3 +226,26 @@ func TestExpireEdgeCase(t *testing.T) {
return c.Len() == 0
})
}

func TestCacheGoGC(t *testing.T) {
capacity := 1_000_000
c := evcache.New[int, byte](capacity)

for i := range capacity {
c.LoadOrStore(i, 0, 0)
}

var stats runtime.MemStats

runtime.ReadMemStats(&stats)
t.Logf("alloc before:\t%d bytes", stats.Alloc)

runtime.KeepAlive(c)

// Run GC twice to account for the finalizer.
runtime.GC()
runtime.GC()

runtime.ReadMemStats(&stats)
t.Logf("alloc after:\t%d bytes", stats.Alloc)
}
4 changes: 2 additions & 2 deletions internal/backend/backend_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,12 +199,12 @@ func assertCacheLen[K comparable, V any](t *testing.T, be *backend.Backend[K, V]
Equal(t, getMapRangeCount(be), n)
}

func fillCache(t *testing.T, b *backend.Backend[int, int], capacity int) {
func fillCache[V any](t *testing.T, b *backend.Backend[int, V], capacity int) {
for i := 0; i < capacity; i++ {
elem := b.Reserve(i)
_, loaded := b.LoadOrStore(elem)
Equal(t, loaded, false)
b.Initialize(elem, 0, 0)
b.Initialize(elem, *new(V), 0)
}

assertCacheLen(t, b, capacity)
Expand Down

0 comments on commit f4d834c

Please sign in to comment.