| 1 | package gocache |
| 2 | |
| 3 | import ( |
| 4 | "log" |
| 5 | "time" |
| 6 | ) |
| 7 | |
| 8 | const ( |
| 9 | // JanitorShiftTarget is the target number of expired keys to find during passive clean up duty |
| 10 | // before pausing the passive expired keys eviction process |
| 11 | JanitorShiftTarget = 25 |
| 12 | |
| 13 | // JanitorMaxIterationsPerShift is the maximum number of nodes to traverse before pausing |
| 14 | // |
| 15 | // This is to prevent the janitor from traversing the entire cache, which could take a long time |
| 16 | // to complete depending on the size of the cache. |
| 17 | // |
| 18 | // By limiting it to a small number, we are effectively reducing the impact of passive eviction. |
| 19 | JanitorMaxIterationsPerShift = 1000 |
| 20 | |
| 21 | // JanitorMinShiftBackOff is the minimum interval between each iteration of steps |
| 22 | // defined by JanitorMaxIterationsPerShift |
| 23 | JanitorMinShiftBackOff = 50 * time.Millisecond |
| 24 | |
| 25 | // JanitorMaxShiftBackOff is the maximum interval between each iteration of steps |
| 26 | // defined by JanitorMaxIterationsPerShift |
| 27 | JanitorMaxShiftBackOff = 500 * time.Millisecond |
| 28 | ) |
| 29 | |
| 30 | // StartJanitor starts the janitor on a different goroutine |
| 31 | // The janitor's job is to delete expired keys in the background, in other words, it takes care of passive eviction. |
| 32 | // It can be stopped by calling Cache.StopJanitor. |
| 33 | // If you do not start the janitor, expired keys will only be deleted when they are accessed through Get, GetByKeys, or |
| 34 | // GetAll. |
| 35 | func (cache *Cache) StartJanitor() error { |
| 36 | if cache.stopJanitor != nil { |
| 37 | return ErrJanitorAlreadyRunning |
| 38 | } |
| 39 | cache.stopJanitor = make(chan bool) |
| 40 | go func() { |
| 41 | // rather than starting from the tail on every run, we can try to start from the last traversed entry |
| 42 | var lastTraversedNode *Entry |
| 43 | totalNumberOfExpiredKeysInPreviousRunFromTailToHead := 0 |
| 44 | backOff := JanitorMinShiftBackOff |
| 45 | for { |
| 46 | select { |
| 47 | case <-time.After(backOff): |
| 48 | // Passive clean up duty |
| 49 | cache.mutex.Lock() |
| 50 | if cache.tail != nil { |
| 51 | start := time.Now() |
| 52 | steps := 0 |
| 53 | expiredEntriesFound := 0 |
| 54 | current := cache.tail |
| 55 | if lastTraversedNode != nil { |
| 56 | // Make sure the lastTraversedNode is still in the cache, otherwise we might be traversing nodes that were already deleted. |
| 57 | // Furthermore, we need to make sure that the entry from the cache has the same pointer as the lastTraversedNode |
| 58 | // to verify that there isn't just a new cache entry with the same key (i.e. in case lastTraversedNode got evicted) |
| 59 | if entryFromCache, isInCache := cache.get(lastTraversedNode.Key); isInCache && entryFromCache == lastTraversedNode { |
| 60 | current = lastTraversedNode |
| 61 | } |
| 62 | } |
| 63 | if current == cache.tail { |
| 64 | if Debug { |
| 65 | log.Printf("There are currently %d entries in the cache. The last walk resulted in finding %d expired keys", len(cache.entries), totalNumberOfExpiredKeysInPreviousRunFromTailToHead) |
| 66 | } |
| 67 | totalNumberOfExpiredKeysInPreviousRunFromTailToHead = 0 |
| 68 | } |
| 69 | for current != nil { |
| 70 | // since we're walking from the tail to the head, we get the previous reference |
| 71 | var previous *Entry |
| 72 | steps++ |
| 73 | if current.Expired() { |
| 74 | expiredEntriesFound++ |
| 75 | // Because delete will remove the previous reference from the entry, we need to store the |
| 76 | // previous reference before we delete it |
| 77 | previous = current.previous |
| 78 | cache.delete(current.Key) |
| 79 | cache.stats.ExpiredKeys++ |
| 80 | } |
| 81 | if current == cache.head { |
| 82 | lastTraversedNode = nil |
| 83 | break |
| 84 | } |
| 85 | // Travel to the current node's previous node only if no specific previous node has been specified |
| 86 | if previous != nil { |
| 87 | current = previous |
| 88 | } else { |
| 89 | current = current.previous |
| 90 | } |
| 91 | lastTraversedNode = current |
| 92 | if steps == JanitorMaxIterationsPerShift || expiredEntriesFound >= JanitorShiftTarget { |
| 93 | if expiredEntriesFound > 0 { |
| 94 | backOff = JanitorMinShiftBackOff |
| 95 | } else { |
| 96 | if backOff*2 <= JanitorMaxShiftBackOff { |
| 97 | backOff *= 2 |
| 98 | } else { |
| 99 | backOff = JanitorMaxShiftBackOff |
| 100 | } |
| 101 | } |
| 102 | break |
| 103 | } |
| 104 | } |
| 105 | if Debug { |
| 106 | log.Printf("traversed %d nodes and found %d expired entries in %s before stopping\n", steps, expiredEntriesFound, time.Since(start)) |
| 107 | } |
| 108 | totalNumberOfExpiredKeysInPreviousRunFromTailToHead += expiredEntriesFound |
| 109 | } else { |
| 110 | if backOff*2 < JanitorMaxShiftBackOff { |
| 111 | backOff *= 2 |
| 112 | } else { |
| 113 | backOff = JanitorMaxShiftBackOff |
| 114 | } |
| 115 | } |
| 116 | cache.mutex.Unlock() |
| 117 | case <-cache.stopJanitor: |
| 118 | cache.stopJanitor <- true |
| 119 | return |
| 120 | } |
| 121 | } |
| 122 | }() |
| 123 | //if Debug { |
| 124 | // go func() { |
| 125 | // var m runtime.MemStats |
| 126 | // for { |
| 127 | // runtime.ReadMemStats(&m) |
| 128 | // log.Printf("Alloc=%vMB; HeapReleased=%vMB; Sys=%vMB; HeapInUse=%vMB; HeapObjects=%v; HeapObjectsFreed=%v; GC=%v; cache.memoryUsage=%vMB; cacheSize=%d\n", m.Alloc/1024/1024, m.HeapReleased/1024/1024, m.Sys/1024/1024, m.HeapInuse/1024/1024, m.HeapObjects, m.Frees, m.NumGC, cache.memoryUsage/1024/1024, cache.Count()) |
| 129 | // time.Sleep(3 * time.Second) |
| 130 | // } |
| 131 | // }() |
| 132 | //} |
| 133 | return nil |
| 134 | } |
| 135 | |
| 136 | // StopJanitor stops the janitor |
| 137 | func (cache *Cache) StopJanitor() { |
| 138 | if cache.stopJanitor != nil { |
| 139 | // Tell the janitor to stop, and then wait for the janitor to reply on the same channel that it's stopping |
| 140 | // This may seem a bit odd, but this allows us to avoid a data race condition when trying to set |
| 141 | // cache.stopJanitor to nil |
| 142 | cache.stopJanitor <- true |
| 143 | <-cache.stopJanitor |
| 144 | cache.stopJanitor = nil |
| 145 | } |
| 146 | } |