github.com/timstclair/heapster@v0.20.0-alpha1/Godeps/_workspace/src/k8s.io/kubernetes/pkg/util/cache.go (about)

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