From ce2c48e770f1ffffaf79c251377d3940a91612f3 Mon Sep 17 00:00:00 2001 From: Derek Collison Date: Wed, 7 Nov 2012 14:31:37 -0800 Subject: [PATCH] Added random eviction functionality --- hashmap/rand_evict.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 hashmap/rand_evict.go diff --git a/hashmap/rand_evict.go b/hashmap/rand_evict.go new file mode 100644 index 00000000..fc065961 --- /dev/null +++ b/hashmap/rand_evict.go @@ -0,0 +1,43 @@ +// Copyright 2012 Apcera Inc. All rights reserved. + +package hashmap + +import ( + "math/rand" + "time" +) + +// We use init to setup the random number generator +func init() { + rand.Seed(time.Now().UnixNano()) +} + +// RemoveRandom can be used for a random policy eviction. +// This is stochastic but very fast and does not impedede +// performance like LRU, LFU or even ARC based implementations. +func (h *HashMap) RemoveRandom() { + if h.used == 0 { + return + } + index := (rand.Int())&int(h.msk) + // Walk forward til we find an entry + for i := index ; i < len(h.bkts) ; i++ { + e := &h.bkts[i] + if *e != nil { + *e = (*e).next + h.used -= 1 + return + } + } + // If we are here we hit end and did not remove anything, + // use the index and walk backwards. + for i := index ; i >= 0 ; i-- { + e := &h.bkts[i] + if *e != nil { + *e = (*e).next + h.used -= 1 + return + } + } + panic("Should not reach here..") +}