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 {@link 033 * #put}, {@link #invalidateAll(Iterable)} is implemented in terms of {@link #invalidate}. The 034 * method {@link #cleanUp} is a no-op. All other methods throw an {@link 035 * 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 /* 064 * <? extends Object> is mostly the same as <?> to plain Java. But to nullness checkers, they 065 * differ: <? extends Object> means "non-null types," while <?> means "all types." 066 */ 067 @Override 068 public ImmutableMap<K, V> getAllPresent(Iterable<? extends Object> keys) { 069 Map<K, V> result = Maps.newLinkedHashMap(); 070 for (Object key : keys) { 071 if (!result.containsKey(key)) { 072 @SuppressWarnings("unchecked") 073 K castKey = (K) key; 074 V value = getIfPresent(key); 075 if (value != null) { 076 result.put(castKey, value); 077 } 078 } 079 } 080 return ImmutableMap.copyOf(result); 081 } 082 083 /** 084 * @since 11.0 085 */ 086 @Override 087 public void put(K key, V value) { 088 throw new UnsupportedOperationException(); 089 } 090 091 /** 092 * @since 12.0 093 */ 094 @Override 095 public void putAll(Map<? extends K, ? extends V> m) { 096 for (Entry<? extends K, ? extends V> entry : m.entrySet()) { 097 put(entry.getKey(), entry.getValue()); 098 } 099 } 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 // For discussion of <? extends Object>, see getAllPresent. 119 public void invalidateAll(Iterable<? extends Object> keys) { 120 for (Object key : keys) { 121 invalidate(key); 122 } 123 } 124 125 @Override 126 public void invalidateAll() { 127 throw new UnsupportedOperationException(); 128 } 129 130 @Override 131 public CacheStats stats() { 132 throw new UnsupportedOperationException(); 133 } 134 135 @Override 136 public ConcurrentMap<K, V> asMap() { 137 throw new UnsupportedOperationException(); 138 } 139 140 /** 141 * Accumulates statistics during the operation of a {@link Cache} for presentation by {@link 142 * Cache#stats}. This is solely intended for consumption by {@code Cache} implementors. 143 * 144 * @since 10.0 145 */ 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 not 157 * found in the cache. This method should be called by the loading thread, as well as by threads 158 * blocking on the load. Multiple concurrent calls to {@link Cache} lookup methods with the same 159 * key on an absent value should result in a single call to either {@code recordLoadSuccess} or 160 * {@code recordLoadException} and multiple calls to this method, despite all being served by 161 * 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 causes 170 * an entry to be loaded, and the loading completes successfully. In contrast to {@link 171 * #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 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 177 void recordLoadSuccess(long loadTime); 178 179 /** 180 * Records the failed load of a new entry. This should be called when a cache request causes an 181 * entry to be loaded, but an exception is thrown while loading the entry. In contrast to {@link 182 * #recordMisses}, this method should only be called by the loading thread. 183 * 184 * @param loadTime the number of nanoseconds the cache spent computing or retrieving the new 185 * value prior to an exception being thrown 186 */ 187 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 188 void recordLoadException(long loadTime); 189 190 /** 191 * Records the eviction of an entry from the cache. This should only been called when an entry 192 * is evicted due to the cache's eviction strategy, and not as a result of manual {@linkplain 193 * Cache#invalidate invalidations}. 194 */ 195 void recordEviction(); 196 197 /** 198 * Returns a snapshot of this counter's values. Note that this may be an inconsistent view, as 199 * it may be interleaved with update operations. 200 */ 201 CacheStats snapshot(); 202 } 203 204 /** 205 * A thread-safe {@link StatsCounter} implementation for use by {@link Cache} implementors. 206 * 207 * @since 10.0 208 */ 209 public static final class SimpleStatsCounter implements StatsCounter { 210 private final LongAddable hitCount = LongAddables.create(); 211 private final LongAddable missCount = LongAddables.create(); 212 private final LongAddable loadSuccessCount = LongAddables.create(); 213 private final LongAddable loadExceptionCount = LongAddables.create(); 214 private final LongAddable totalLoadTime = LongAddables.create(); 215 private final LongAddable evictionCount = LongAddables.create(); 216 217 /** Constructs an instance with all counts initialized to zero. */ 218 public SimpleStatsCounter() {} 219 220 /** 221 * @since 11.0 222 */ 223 @Override 224 public void recordHits(int count) { 225 hitCount.add(count); 226 } 227 228 /** 229 * @since 11.0 230 */ 231 @Override 232 public void recordMisses(int count) { 233 missCount.add(count); 234 } 235 236 @SuppressWarnings("GoodTime") // b/122668874 237 @Override 238 public void recordLoadSuccess(long loadTime) { 239 loadSuccessCount.increment(); 240 totalLoadTime.add(loadTime); 241 } 242 243 @SuppressWarnings("GoodTime") // b/122668874 244 @Override 245 public void recordLoadException(long loadTime) { 246 loadExceptionCount.increment(); 247 totalLoadTime.add(loadTime); 248 } 249 250 @Override 251 public void recordEviction() { 252 evictionCount.increment(); 253 } 254 255 @Override 256 public CacheStats snapshot() { 257 return new CacheStats( 258 negativeToMaxValue(hitCount.sum()), 259 negativeToMaxValue(missCount.sum()), 260 negativeToMaxValue(loadSuccessCount.sum()), 261 negativeToMaxValue(loadExceptionCount.sum()), 262 negativeToMaxValue(totalLoadTime.sum()), 263 negativeToMaxValue(evictionCount.sum())); 264 } 265 266 /** Returns {@code value}, if non-negative. Otherwise, returns {@link Long#MAX_VALUE}. */ 267 private static long negativeToMaxValue(long value) { 268 return (value >= 0) ? value : Long.MAX_VALUE; 269 } 270 271 /** Increments all counters by the values in {@code other}. */ 272 public void incrementBy(StatsCounter other) { 273 CacheStats otherStats = other.snapshot(); 274 hitCount.add(otherStats.hitCount()); 275 missCount.add(otherStats.missCount()); 276 loadSuccessCount.add(otherStats.loadSuccessCount()); 277 loadExceptionCount.add(otherStats.loadExceptionCount()); 278 totalLoadTime.add(otherStats.totalLoadTime()); 279 evictionCount.add(otherStats.evictionCount()); 280 } 281 } 282}