001/* 002 * Copyright (C) 2011 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.cache; 016 017import com.google.common.annotations.GwtCompatible; 018import com.google.common.collect.ImmutableMap; 019import com.google.common.collect.Maps; 020import java.util.Map; 021import java.util.Map.Entry; 022import java.util.concurrent.Callable; 023import java.util.concurrent.ConcurrentMap; 024import java.util.concurrent.ExecutionException; 025 026/** 027 * This class provides a skeletal implementation of the {@code Cache} interface to minimize the 028 * effort required to implement this interface. 029 * 030 * <p>To implement a cache, the programmer needs only to extend this class and provide an 031 * implementation for the {@link #put} and {@link #getIfPresent} methods. {@link #getAllPresent} is 032 * implemented in terms of {@link #getIfPresent}; {@link #putAll} is implemented in terms of 033 * {@link #put}, {@link #invalidateAll(Iterable)} is implemented in terms of {@link #invalidate}. 034 * The method {@link #cleanUp} is a no-op. All other methods throw an 035 * {@link UnsupportedOperationException}. 036 * 037 * @author Charles Fry 038 * @since 10.0 039 */ 040@GwtCompatible 041public abstract class AbstractCache<K, V> implements Cache<K, V> { 042 043 /** Constructor for use by subclasses. */ 044 protected AbstractCache() {} 045 046 /** 047 * @since 11.0 048 */ 049 @Override 050 public V get(K key, Callable<? extends V> valueLoader) throws ExecutionException { 051 throw new UnsupportedOperationException(); 052 } 053 054 /** 055 * {@inheritDoc} 056 * 057 * <p>This implementation of {@code getAllPresent} lacks any insight into the internal cache data 058 * structure, and is thus forced to return the query keys instead of the cached keys. This is only 059 * possible with an unsafe cast which requires {@code keys} to actually be of type {@code K}. 060 * 061 * @since 11.0 062 */ 063 @Override 064 public ImmutableMap<K, V> getAllPresent(Iterable<?> keys) { 065 Map<K, V> result = Maps.newLinkedHashMap(); 066 for (Object key : keys) { 067 if (!result.containsKey(key)) { 068 @SuppressWarnings("unchecked") 069 K castKey = (K) key; 070 V value = getIfPresent(key); 071 if (value != null) { 072 result.put(castKey, value); 073 } 074 } 075 } 076 return ImmutableMap.copyOf(result); 077 } 078 079 /** 080 * @since 11.0 081 */ 082 @Override 083 public void put(K key, V value) { 084 throw new UnsupportedOperationException(); 085 } 086 087 /** 088 * @since 12.0 089 */ 090 @Override 091 public void putAll(Map<? extends K, ? extends V> m) { 092 for (Entry<? extends K, ? extends V> entry : m.entrySet()) { 093 put(entry.getKey(), entry.getValue()); 094 } 095 } 096 097 @Override 098 public void cleanUp() {} 099 100 @Override 101 public long size() { 102 throw new UnsupportedOperationException(); 103 } 104 105 @Override 106 public void invalidate(Object key) { 107 throw new UnsupportedOperationException(); 108 } 109 110 /** 111 * @since 11.0 112 */ 113 @Override 114 public void invalidateAll(Iterable<?> keys) { 115 for (Object key : keys) { 116 invalidate(key); 117 } 118 } 119 120 @Override 121 public void invalidateAll() { 122 throw new UnsupportedOperationException(); 123 } 124 125 @Override 126 public CacheStats stats() { 127 throw new UnsupportedOperationException(); 128 } 129 130 @Override 131 public ConcurrentMap<K, V> asMap() { 132 throw new UnsupportedOperationException(); 133 } 134 135 /** 136 * Accumulates statistics during the operation of a {@link Cache} for presentation by 137 * {@link Cache#stats}. This is solely intended for consumption by {@code Cache} implementors. 138 * 139 * @since 10.0 140 */ 141 public interface StatsCounter { 142 /** 143 * Records cache hits. This should be called when a cache request returns a cached value. 144 * 145 * @param count the number of hits to record 146 * @since 11.0 147 */ 148 void recordHits(int count); 149 150 /** 151 * Records cache misses. This should be called when a cache request returns a value that was not 152 * found in the cache. This method should be called by the loading thread, as well as by threads 153 * blocking on the load. Multiple concurrent calls to {@link Cache} lookup methods with the same 154 * key on an absent value should result in a single call to either {@code recordLoadSuccess} or 155 * {@code recordLoadException} and multiple calls to this method, despite all being served by 156 * the results of a single load operation. 157 * 158 * @param count the number of misses to record 159 * @since 11.0 160 */ 161 void recordMisses(int count); 162 163 /** 164 * Records the successful load of a new entry. This should be called when a cache request causes 165 * an entry to be loaded, and the loading completes successfully. In contrast to 166 * {@link #recordMisses}, this method should only be called by the loading thread. 167 * 168 * @param loadTime the number of nanoseconds the cache spent computing or retrieving the new 169 * value 170 */ 171 void recordLoadSuccess(long loadTime); 172 173 /** 174 * Records the failed load of a new entry. This should be called when a cache request causes an 175 * entry to be loaded, but an exception is thrown while loading the entry. In contrast to 176 * {@link #recordMisses}, this method should only be called by the loading thread. 177 * 178 * @param loadTime the number of nanoseconds the cache spent computing or retrieving the new 179 * value prior to an exception being thrown 180 */ 181 void recordLoadException(long loadTime); 182 183 /** 184 * Records the eviction of an entry from the cache. This should only been called when an entry 185 * is evicted due to the cache's eviction strategy, and not as a result of manual 186 * {@linkplain Cache#invalidate invalidations}. 187 */ 188 void recordEviction(); 189 190 /** 191 * Returns a snapshot of this counter's values. Note that this may be an inconsistent view, as 192 * it may be interleaved with update operations. 193 */ 194 CacheStats snapshot(); 195 } 196 197 /** 198 * A thread-safe {@link StatsCounter} implementation for use by {@link Cache} implementors. 199 * 200 * @since 10.0 201 */ 202 public static final class SimpleStatsCounter implements StatsCounter { 203 private final LongAddable hitCount = LongAddables.create(); 204 private final LongAddable missCount = LongAddables.create(); 205 private final LongAddable loadSuccessCount = LongAddables.create(); 206 private final LongAddable loadExceptionCount = LongAddables.create(); 207 private final LongAddable totalLoadTime = LongAddables.create(); 208 private final LongAddable evictionCount = LongAddables.create(); 209 210 /** 211 * Constructs an instance with all counts initialized to zero. 212 */ 213 public SimpleStatsCounter() {} 214 215 /** 216 * @since 11.0 217 */ 218 @Override 219 public void recordHits(int count) { 220 hitCount.add(count); 221 } 222 223 /** 224 * @since 11.0 225 */ 226 @Override 227 public void recordMisses(int count) { 228 missCount.add(count); 229 } 230 231 @Override 232 public void recordLoadSuccess(long loadTime) { 233 loadSuccessCount.increment(); 234 totalLoadTime.add(loadTime); 235 } 236 237 @Override 238 public void recordLoadException(long loadTime) { 239 loadExceptionCount.increment(); 240 totalLoadTime.add(loadTime); 241 } 242 243 @Override 244 public void recordEviction() { 245 evictionCount.increment(); 246 } 247 248 @Override 249 public CacheStats snapshot() { 250 return new CacheStats( 251 hitCount.sum(), 252 missCount.sum(), 253 loadSuccessCount.sum(), 254 loadExceptionCount.sum(), 255 totalLoadTime.sum(), 256 evictionCount.sum()); 257 } 258 259 /** 260 * Increments all counters by the values in {@code other}. 261 */ 262 public void incrementBy(StatsCounter other) { 263 CacheStats otherStats = other.snapshot(); 264 hitCount.add(otherStats.hitCount()); 265 missCount.add(otherStats.missCount()); 266 loadSuccessCount.add(otherStats.loadSuccessCount()); 267 loadExceptionCount.add(otherStats.loadExceptionCount()); 268 totalLoadTime.add(otherStats.totalLoadTime()); 269 evictionCount.add(otherStats.evictionCount()); 270 } 271 } 272}