6df1e24ae3
1 - Previously, we determined if an item should be promoted in the main getter thread. This required that we protect the item.promotions variable, as both the getter and the worker were concurrently accessing it. This change pushes the conditional promotion to the worker (from the getter's point of view, items are always promoted). Since only the worker ever accesses .promotions, we no longer must protect access to it. 2 - The total size of the cache was being maintained by both the worker thread and the calling code. This required that we protect access to cache.size. Now, only the worker ever changes the size. While this simplifies much of the code, it means that we can't easily replace an item (replacement either via Set or Replace). A replcement now involves creating a new object and deleting the old one (using the existing deletables and promotable infrastructure). The only noticeable impact frmo this change is that, despite previous documentation, Replace WILL cause the item to be promoted (but it still only does so if it exists and it still doesn't extend the original TTL).
74 lines
1.4 KiB
Go
74 lines
1.4 KiB
Go
package ccache
|
|
|
|
import (
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type layeredBucket struct {
|
|
sync.RWMutex
|
|
buckets map[string]*bucket
|
|
}
|
|
|
|
func (b *layeredBucket) get(primary, secondary string) *Item {
|
|
b.RLock()
|
|
bucket, exists := b.buckets[primary]
|
|
b.RUnlock()
|
|
if exists == false {
|
|
return nil
|
|
}
|
|
return bucket.get(secondary)
|
|
}
|
|
|
|
func (b *layeredBucket) set(primary, secondary string, value interface{}, duration time.Duration) (*Item, *Item) {
|
|
b.Lock()
|
|
bkt, exists := b.buckets[primary]
|
|
if exists == false {
|
|
bkt = &bucket{lookup: make(map[string]*Item)}
|
|
b.buckets[primary] = bkt
|
|
}
|
|
b.Unlock()
|
|
item, existing := bkt.set(secondary, value, duration)
|
|
item.group = primary
|
|
return item, existing
|
|
}
|
|
|
|
func (b *layeredBucket) delete(primary, secondary string) *Item {
|
|
b.RLock()
|
|
bucket, exists := b.buckets[primary]
|
|
b.RUnlock()
|
|
if exists == false {
|
|
return nil
|
|
}
|
|
return bucket.delete(secondary)
|
|
}
|
|
|
|
func (b *layeredBucket) deleteAll(primary string, deletables chan *Item) bool {
|
|
b.RLock()
|
|
bucket, exists := b.buckets[primary]
|
|
b.RUnlock()
|
|
if exists == false {
|
|
return false
|
|
}
|
|
|
|
bucket.Lock()
|
|
defer bucket.Unlock()
|
|
|
|
if l := len(bucket.lookup); l == 0 {
|
|
return false
|
|
}
|
|
for key, item := range bucket.lookup {
|
|
delete(bucket.lookup, key)
|
|
deletables <- item
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (b *layeredBucket) clear() {
|
|
b.Lock()
|
|
defer b.Unlock()
|
|
for _, bucket := range b.buckets {
|
|
bucket.clear()
|
|
}
|
|
b.buckets = make(map[string]*bucket)
|
|
}
|