|
| 1 | +package decaymap |
| 2 | + |
| 3 | +import ( |
| 4 | + "sync" |
| 5 | + "time" |
| 6 | +) |
| 7 | + |
| 8 | +// DecayMap is a coarse-grained paired map that bulk-frees outdated entries. |
| 9 | +type DecayMap[K comparable, V any] struct { |
| 10 | + mu sync.RWMutex |
| 11 | + maps [2]map[K]V |
| 12 | + epoch time.Time |
| 13 | + lastInsert time.Time |
| 14 | + generation uint64 |
| 15 | + period time.Duration |
| 16 | +} |
| 17 | + |
| 18 | +func NewDecayMap[K comparable, V any](epoch time.Time, period time.Duration) *DecayMap[K, V] { |
| 19 | + return &DecayMap[K, V]{ |
| 20 | + maps: [2]map[K]V{make(map[K]V), make(map[K]V)}, |
| 21 | + epoch: epoch, |
| 22 | + generation: 0, |
| 23 | + period: period, |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +// Attempts to retrieve a value from the store, does not guarantee the value is unexpired. |
| 28 | +func (m *DecayMap[K, V]) Get(key K) (res V, ok bool) { |
| 29 | + m.mu.RLock() |
| 30 | + defer m.mu.RUnlock() |
| 31 | + res, ok = m.maps[0][key] |
| 32 | + if ok { |
| 33 | + return |
| 34 | + } |
| 35 | + res, ok = m.maps[1][key] |
| 36 | + return |
| 37 | +} |
| 38 | + |
| 39 | +// Sets a value in the store, overwriting the existing value if exists. |
| 40 | +// |
| 41 | +// Inserting values in non monotonic order is a no op. |
| 42 | +func (m *DecayMap[K, V]) Set(now time.Time, key K, value V) { |
| 43 | + m.mu.Lock() |
| 44 | + defer m.mu.Unlock() |
| 45 | + if now.Before(m.lastInsert) { |
| 46 | + return |
| 47 | + } |
| 48 | + m.lastInsert = now |
| 49 | + curGen := uint64(now.Sub(m.epoch) / m.period) |
| 50 | + genDelta := curGen - m.generation |
| 51 | + if genDelta >= 2 { |
| 52 | + // both are outdated, clear both |
| 53 | + m.maps[0] = make(map[K]V) |
| 54 | + m.maps[1] = make(map[K]V) |
| 55 | + m.generation = curGen |
| 56 | + } else if genDelta == 1 { |
| 57 | + // one is outdated, clear the outdated one |
| 58 | + m.maps[curGen&1] = make(map[K]V) |
| 59 | + m.generation = curGen |
| 60 | + } |
| 61 | + delete(m.maps[(curGen&1)^1], key) |
| 62 | + m.maps[curGen&1][key] = value |
| 63 | +} |
0 commit comments