Skip to content

Instantly share code, notes, and snippets.

@hazcod
Created September 15, 2020 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hazcod/8f6dee847ca35ce273d62ac1c20e4b1d to your computer and use it in GitHub Desktop.
Save hazcod/8f6dee847ca35ce273d62ac1c20e4b1d to your computer and use it in GitHub Desktop.
Go sync.map with TTL and per-second scavenging
type TTLMap struct {
TTL time.Duration
data sync.Map
}
type expireEntry struct {
ExpiresAt time.Time
Value interface{}
}
func (t *ExpiringCertMap) Store(key string, val interface{}) {
t.data.Store(key, expireEntry{
ExpiresAt: time.Now().Add(t.TTL),
Value: val,
})
}
func (t *ExpiringCertMap) Load(key string) (val interface{}) {
entry, ok := t.data.Load(key)
if !ok { return nil }
expireEntry := entry.(expireEntry)
if expireEntry.ExpiresAt.After(time.Now()) { return nil }
return expireEntry.Value
}
func NewTTLMap(ttl time.Duration) (m ExpiringCertMap) {
m.TTL = ttl
go func() {
for now := range time.Tick(time.Second) {
m.data.Range(func(k, v interface{}) bool {
if v.(expireEntry).ExpiresAt.After(now) {
m.data.Delete(k)
}
return true
})
}
}()
return
}
@thediveo
Copy link

thediveo commented Sep 5, 2022

leaks the goroutine, which may not or may be a problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment