cache.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cache
  14. import (
  15. "sync"
  16. )
  17. const (
  18. shardsCount int = 32
  19. )
  20. type Cache []*cacheShard
  21. func NewCache(maxSize int) Cache {
  22. if maxSize < shardsCount {
  23. maxSize = shardsCount
  24. }
  25. cache := make(Cache, shardsCount)
  26. for i := 0; i < shardsCount; i++ {
  27. cache[i] = &cacheShard{
  28. items: make(map[uint64]interface{}),
  29. maxSize: maxSize / shardsCount,
  30. }
  31. }
  32. return cache
  33. }
  34. func (c Cache) getShard(index uint64) *cacheShard {
  35. return c[index%uint64(shardsCount)]
  36. }
  37. // Returns true if object already existed, false otherwise.
  38. func (c *Cache) Add(index uint64, obj interface{}) bool {
  39. return c.getShard(index).add(index, obj)
  40. }
  41. func (c *Cache) Get(index uint64) (obj interface{}, found bool) {
  42. return c.getShard(index).get(index)
  43. }
  44. type cacheShard struct {
  45. items map[uint64]interface{}
  46. sync.RWMutex
  47. maxSize int
  48. }
  49. // Returns true if object already existed, false otherwise.
  50. func (s *cacheShard) add(index uint64, obj interface{}) bool {
  51. s.Lock()
  52. defer s.Unlock()
  53. _, isOverwrite := s.items[index]
  54. if !isOverwrite && len(s.items) >= s.maxSize {
  55. var randomKey uint64
  56. for randomKey = range s.items {
  57. break
  58. }
  59. delete(s.items, randomKey)
  60. }
  61. s.items[index] = obj
  62. return isOverwrite
  63. }
  64. func (s *cacheShard) get(index uint64) (obj interface{}, found bool) {
  65. s.RLock()
  66. defer s.RUnlock()
  67. obj, found = s.items[index]
  68. return
  69. }