1 /* 2 * Copyright (C) 2011 The Guava Authors 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 com.google.common.cache; 18 19 import com.google.common.annotations.Beta; 20 import com.google.common.annotations.GwtCompatible; 21 import com.google.common.collect.ImmutableMap; 22 import com.google.common.collect.Maps; 23 24 import java.util.Map; 25 import java.util.concurrent.Callable; 26 import java.util.concurrent.ConcurrentMap; 27 import java.util.concurrent.ExecutionException; 28 29 /** 30 * This class provides a skeletal implementation of the {@code Cache} interface to minimize the 31 * effort required to implement this interface. 32 * 33 * <p>To implement a cache, the programmer needs only to extend this class and provide an 34 * implementation for the {@link #put} and {@link #getIfPresent} methods. {@link #getAllPresent} is 35 * implemented in terms of {@link #getIfPresent}; {@link #putAll} is implemented in terms of 36 * {@link #put}, {@link #invalidateAll(Iterable)} is implemented in terms of {@link #invalidate}. 37 * The method {@link #cleanUp} is a no-op. All other methods throw an 38 * {@link UnsupportedOperationException}. 39 * 40 * @author Charles Fry 41 * @since 10.0 42 */ 43 @Beta 44 @GwtCompatible 45 public abstract class AbstractCache<K, V> implements Cache<K, V> { 46 47 /** Constructor for use by subclasses. */ 48 protected AbstractCache() {} 49 50 /** 51 * @since 11.0 52 */ 53 @Override 54 public V get(K key, Callable<? extends V> valueLoader) throws ExecutionException { 55 throw new UnsupportedOperationException(); 56 } 57 58 /** 59 * This implementation of {@code getAllPresent} lacks any insight into the internal cache data 60 * structure, and is thus forced to return the query keys instead of the cached keys. This is only 61 * possible with an unsafe cast which requires {@code keys} to actually be of type {@code K}. 62 * 63 * {@inheritDoc} 64 * 65 * @since 11.0 66 */ 67 @Override 68 public ImmutableMap<K, V> getAllPresent(Iterable<?> keys) { 69 Map<K, V> result = Maps.newLinkedHashMap(); 70 for (Object key : keys) { 71 if (!result.containsKey(key)) { 72 @SuppressWarnings("unchecked") 73 K castKey = (K) key; 74 V value = getIfPresent(key); 75 if (value != null) { 76 result.put(castKey, value); 77 } 78 } 79 } 80 return ImmutableMap.copyOf(result); 81 } 82 83 /** 84 * @since 11.0 85 */ 86 @Override 87 public void put(K key, V value) { 88 throw new UnsupportedOperationException(); 89 } 90 91 /** 92 * @since 12.0 93 */ 94 @Override 95 public void putAll(Map<? extends K, ? extends V> m) { 96 for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { 97 put(entry.getKey(), entry.getValue()); 98 } 99 } 100 101 @Override 102 public void cleanUp() {} 103 104 @Override 105 public long size() { 106 throw new UnsupportedOperationException(); 107 } 108 109 @Override 110 public void invalidate(Object key) { 111 throw new UnsupportedOperationException(); 112 } 113 114 /** 115 * @since 11.0 116 */ 117 @Override 118 public void invalidateAll(Iterable<?> keys) { 119 for (Object key : keys) { 120 invalidate(key); 121 } 122 } 123 124 @Override 125 public void invalidateAll() { 126 throw new UnsupportedOperationException(); 127 } 128 129 @Override 130 public CacheStats stats() { 131 throw new UnsupportedOperationException(); 132 } 133 134 @Override 135 public ConcurrentMap<K, V> asMap() { 136 throw new UnsupportedOperationException(); 137 } 138 139 /** 140 * Accumulates statistics during the operation of a {@link Cache} for presentation by {@link 141 * Cache#stats}. This is solely intended for consumption by {@code Cache} implementors. 142 * 143 * @since 10.0 144 */ 145 @Beta 146 public interface StatsCounter { 147 /** 148 * Records cache hits. This should be called when a cache request returns a cached value. 149 * 150 * @param count the number of hits to record 151 * @since 11.0 152 */ 153 void recordHits(int count); 154 155 /** 156 * Records cache misses. This should be called when a cache request returns a value that was 157 * not found in the cache. This method should be called by the loading thread, as well as by 158 * threads blocking on the load. Multiple concurrent calls to {@link Cache} lookup methods with 159 * the same key on an absent value should result in a single call to either 160 * {@code recordLoadSuccess} or {@code recordLoadException} and multiple calls to this method, 161 * despite all being served by the results of a single load operation. 162 * 163 * @param count the number of misses to record 164 * @since 11.0 165 */ 166 void recordMisses(int count); 167 168 /** 169 * Records the successful load of a new entry. This should be called when a cache request 170 * causes an entry to be loaded, and the loading completes successfully. In contrast to 171 * {@link #recordMisses}, this method should only be called by the loading thread. 172 * 173 * @param loadTime the number of nanoseconds the cache spent computing or retrieving the new 174 * value 175 */ 176 void recordLoadSuccess(long loadTime); 177 178 /** 179 * Records the failed load of a new entry. This should be called when a cache request causes 180 * an entry to be loaded, but an exception is thrown while loading the entry. In contrast to 181 * {@link #recordMisses}, this method should only be called by the loading thread. 182 * 183 * @param loadTime the number of nanoseconds the cache spent computing or retrieving the new 184 * value prior to an exception being thrown 185 */ 186 void recordLoadException(long loadTime); 187 188 /** 189 * Records the eviction of an entry from the cache. This should only been called when an entry 190 * is evicted due to the cache's eviction strategy, and not as a result of manual {@linkplain 191 * Cache#invalidate invalidations}. 192 */ 193 void recordEviction(); 194 195 /** 196 * Returns a snapshot of this counter's values. Note that this may be an inconsistent view, as 197 * it may be interleaved with update operations. 198 */ 199 CacheStats snapshot(); 200 } 201 202 /** 203 * A thread-safe {@link StatsCounter} implementation for use by {@link Cache} implementors. 204 * 205 * @since 10.0 206 */ 207 @Beta 208 public static final class SimpleStatsCounter implements StatsCounter { 209 private final LongAddable hitCount = LongAddables.create(); 210 private final LongAddable missCount = LongAddables.create(); 211 private final LongAddable loadSuccessCount = LongAddables.create(); 212 private final LongAddable loadExceptionCount = LongAddables.create(); 213 private final LongAddable totalLoadTime = LongAddables.create(); 214 private final LongAddable evictionCount = LongAddables.create(); 215 216 /** 217 * Constructs an instance with all counts initialized to zero. 218 */ 219 public SimpleStatsCounter() {} 220 221 /** 222 * @since 11.0 223 */ 224 @Override 225 public void recordHits(int count) { 226 hitCount.add(count); 227 } 228 229 /** 230 * @since 11.0 231 */ 232 @Override 233 public void recordMisses(int count) { 234 missCount.add(count); 235 } 236 237 @Override 238 public void recordLoadSuccess(long loadTime) { 239 loadSuccessCount.increment(); 240 totalLoadTime.add(loadTime); 241 } 242 243 @Override 244 public void recordLoadException(long loadTime) { 245 loadExceptionCount.increment(); 246 totalLoadTime.add(loadTime); 247 } 248 249 @Override 250 public void recordEviction() { 251 evictionCount.increment(); 252 } 253 254 @Override 255 public CacheStats snapshot() { 256 return new CacheStats( 257 hitCount.sum(), 258 missCount.sum(), 259 loadSuccessCount.sum(), 260 loadExceptionCount.sum(), 261 totalLoadTime.sum(), 262 evictionCount.sum()); 263 } 264 265 /** 266 * Increments all counters by the values in {@code other}. 267 */ 268 public void incrementBy(StatsCounter other) { 269 CacheStats otherStats = other.snapshot(); 270 hitCount.add(otherStats.hitCount()); 271 missCount.add(otherStats.missCount()); 272 loadSuccessCount.add(otherStats.loadSuccessCount()); 273 loadExceptionCount.add(otherStats.loadExceptionCount()); 274 totalLoadTime.add(otherStats.totalLoadTime()); 275 evictionCount.add(otherStats.evictionCount()); 276 } 277 } 278 } 279