From 94cc221625331b9bedb069814586c7c877a8fcc1 Mon Sep 17 00:00:00 2001 From: Jan-Lukas Else Date: Sat, 13 Mar 2021 13:17:42 +0100 Subject: [PATCH] Added regular garbage collection --- cache.go | 5 ----- garbagecollector.go | 24 ++++++++++++++++++++++++ http.go | 6 ------ main.go | 3 +++ 4 files changed, 27 insertions(+), 11 deletions(-) create mode 100644 garbagecollector.go diff --git a/cache.go b/cache.go index 071d075..f42b378 100644 --- a/cache.go +++ b/cache.go @@ -9,7 +9,6 @@ import ( "net/http" "net/http/httptest" "net/url" - "runtime" "strconv" "strings" "time" @@ -211,10 +210,6 @@ func getCache(key string, next http.Handler, r *http.Request) (item *cacheItem) func purgeCache() { cacheR.Clear() - // Do manual GC - go func() { - runtime.GC() - }() } func setInternalCacheExpirationHeader(w http.ResponseWriter, expiration int) { diff --git a/garbagecollector.go b/garbagecollector.go new file mode 100644 index 0000000..76ded2d --- /dev/null +++ b/garbagecollector.go @@ -0,0 +1,24 @@ +package main + +import ( + "log" + "runtime" + "time" +) + +func initGC() { + go func() { + ticker := time.NewTicker(10 * time.Minute) + for range ticker.C { + go doGC() + } + }() +} + +func doGC() { + var old, new runtime.MemStats + runtime.ReadMemStats(&old) + runtime.GC() + runtime.ReadMemStats(&new) + log.Printf("Alloc: %v MiB → %v MiB", old.Alloc/1024/1024, new.Alloc/1024/1024) +} diff --git a/http.go b/http.go index 3c7c2ed..ec2ed0e 100644 --- a/http.go +++ b/http.go @@ -6,7 +6,6 @@ import ( "log" "net/http" "net/url" - "runtime" "strconv" "strings" "sync/atomic" @@ -90,11 +89,6 @@ func reloadRouter() error { } purgeCache() d.swapHandler(h) - // Do manual GC - go func() { - time.Sleep(10 * time.Second) - runtime.GC() - }() return nil } diff --git a/main.go b/main.go index 91ee25a..70b6c1e 100644 --- a/main.go +++ b/main.go @@ -52,6 +52,9 @@ func main() { } } + // Init regular garbage collection + initGC() + // Execute pre-start hooks preStartHooks() // Initialize everything else