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