add Stop method to stop the background worker and make it possible for the GC to reap the object

This commit is contained in:
Karl Seguin 2015-07-23 22:24:50 +08:00
parent 41f1a3cfcb
commit bfa769c6b6
2 changed files with 14 additions and 1 deletions

View file

@ -115,6 +115,12 @@ func (c *Cache) Clear() {
c.list = list.New()
}
// Stops the background worker. Operations performed on the cache after Stop
// is called are likely to panic
func (c *Cache) Stop() {
close(c.promotables)
}
func (c *Cache) deleteItem(bucket *bucket, item *Item) {
bucket.delete(item.key) //stop other GETs from getting it
c.deletables <- item
@ -142,7 +148,10 @@ func (c *Cache) promote(item *Item) {
func (c *Cache) worker() {
for {
select {
case item := <-c.promotables:
case item, ok := <-c.promotables:
if ok == false {
return
}
if c.doPromote(item) && c.size > c.maxSize {
c.gc()
}

View file

@ -101,6 +101,10 @@ cache.Replace("user:4", user)
`Replace` returns true if the item existed (and thus was replaced). In the case where the key was not in the cache, the value *is not* inserted and false is returned.
### Stop
The cache's background worker can be stopped by calling `Stop`. Once `Stop` is called
the cache should not be used (calls are likely to panic). Stop must be called in order to allow the garbage collector to reap the cache.
## Tracking
CCache supports a special tracking mode which is meant to be used in conjunction with other pieces of your code that maintains a long-lived reference to data.