From f4d834c9af6e441acb02f303eee6e4bc140f02c0 Mon Sep 17 00:00:00 2001 From: Magnus Kokk Date: Mon, 29 Apr 2024 23:40:46 +0300 Subject: [PATCH] Test cache finalizer --- cache.go | 8 +++----- cache_test.go | 24 ++++++++++++++++++++++++ internal/backend/backend_test.go | 4 ++-- 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/cache.go b/cache.go index e59f600..8bce266 100644 --- a/cache.go +++ b/cache.go @@ -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 diff --git a/cache_test.go b/cache_test.go index 24c9b92..71e5e77 100644 --- a/cache_test.go +++ b/cache_test.go @@ -2,6 +2,7 @@ package evcache_test import ( "fmt" + "runtime" "testing" "time" @@ -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) +} diff --git a/internal/backend/backend_test.go b/internal/backend/backend_test.go index 5980f44..f6ccf06 100644 --- a/internal/backend/backend_test.go +++ b/internal/backend/backend_test.go @@ -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)