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 041@ElementTypesAreNonnullByDefault 042public abstract class AbstractCache<K, V> implements Cache<K, V> { 043 044 /** Constructor for use by subclasses. */ 045 protected AbstractCache() {} 046 047 /** @since 11.0 */ 048 @Override 049 public V get(K key, Callable<? extends V> valueLoader) throws ExecutionException { 050 throw new UnsupportedOperationException(); 051 } 052 053 /** 054 * {@inheritDoc} 055 * 056 * <p>This implementation of {@code getAllPresent} lacks any insight into the internal cache data 057 * structure, and is thus forced to return the query keys instead of the cached keys. This is only 058 * possible with an unsafe cast which requires {@code keys} to actually be of type {@code K}. 059 * 060 * @since 11.0 061 */ 062 /* 063 * <? extends Object> is mostly the same as <?> to plain Java. But to nullness checkers, they 064 * differ: <? extends Object> means "non-null types," while <?> means "all types." 065 */ 066 @Override 067 public ImmutableMap<K, V> getAllPresent(Iterable<? extends Object> keys) { 068 Map<K, V> result = Maps.newLinkedHashMap(); 069 for (Object key : keys) { 070 if (!result.containsKey(key)) { 071 @SuppressWarnings("unchecked") 072 K castKey = (K) key; 073 V value = getIfPresent(key); 074 if (value != null) { 075 result.put(castKey, value); 076 } 077 } 078 } 079 return ImmutableMap.copyOf(result); 080 } 081 082 /** @since 11.0 */ 083 @Override 084 public void put(K key, V value) { 085 throw new UnsupportedOperationException(); 086 } 087 088 /** @since 12.0 */ 089 @Override 090 public void putAll(Map<? extends K, ? extends V> m) { 091 for (Entry<? extends K, ? extends V> entry : m.entrySet()) { 092 put(entry.getKey(), entry.getValue()); 093 } 094 } 095 096 @Override 097 public void cleanUp() {} 098 099 @Override 100 public long size() { 101 throw new UnsupportedOperationException(); 102 } 103 104 @Override 105 public void invalidate(Object key) { 106 throw new UnsupportedOperationException(); 107 } 108 109 /** @since 11.0 */ 110 @Override 111 // For discussion of <? extends Object>, see getAllPresent. 112 public void invalidateAll(Iterable<? extends Object> keys) { 113 for (Object key : keys) { 114 invalidate(key); 115 } 116 } 117 118 @Override 119 public void invalidateAll() { 120 throw new UnsupportedOperationException(); 121 } 122 123 @Override 124 public CacheStats stats() { 125 throw new UnsupportedOperationException(); 126 } 127 128 @Override 129 public ConcurrentMap<K, V> asMap() { 130 throw new UnsupportedOperationException(); 131 } 132 133 /** 134 * Accumulates statistics during the operation of a {@link Cache} for presentation by {@link 135 * Cache#stats}. This is solely intended for consumption by {@code Cache} implementors. 136 * 137 * @since 10.0 138 */ 139 public interface StatsCounter { 140 /** 141 * Records cache hits. This should be called when a cache request returns a cached value. 142 * 143 * @param count the number of hits to record 144 * @since 11.0 145 */ 146 void recordHits(int count); 147 148 /** 149 * Records cache misses. This should be called when a cache request returns a value that was not 150 * found in the cache. This method should be called by the loading thread, as well as by threads 151 * blocking on the load. Multiple concurrent calls to {@link Cache} lookup methods with the same 152 * key on an absent value should result in a single call to either {@code recordLoadSuccess} or 153 * {@code recordLoadException} and multiple calls to this method, despite all being served by 154 * the results of a single load operation. 155 * 156 * @param count the number of misses to record 157 * @since 11.0 158 */ 159 void recordMisses(int count); 160 161 /** 162 * Records the successful load of a new entry. This should be called when a cache request causes 163 * an entry to be loaded, and the loading completes successfully. In contrast to {@link 164 * #recordMisses}, this method should only be called by the loading thread. 165 * 166 * @param loadTime the number of nanoseconds the cache spent computing or retrieving the new 167 * value 168 */ 169 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 170 void recordLoadSuccess(long loadTime); 171 172 /** 173 * Records the failed load of a new entry. This should be called when a cache request causes an 174 * entry to be loaded, but an exception is thrown while loading the entry. In contrast to {@link 175 * #recordMisses}, this method should only be called by the loading thread. 176 * 177 * @param loadTime the number of nanoseconds the cache spent computing or retrieving the new 178 * value prior to an exception being thrown 179 */ 180 @SuppressWarnings("GoodTime") // should accept a java.time.Duration 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 {@linkplain 186 * 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 /** Constructs an instance with all counts initialized to zero. */ 211 public SimpleStatsCounter() {} 212 213 /** @since 11.0 */ 214 @Override 215 public void recordHits(int count) { 216 hitCount.add(count); 217 } 218 219 /** @since 11.0 */ 220 @Override 221 public void recordMisses(int count) { 222 missCount.add(count); 223 } 224 225 @SuppressWarnings("GoodTime") // b/122668874 226 @Override 227 public void recordLoadSuccess(long loadTime) { 228 loadSuccessCount.increment(); 229 totalLoadTime.add(loadTime); 230 } 231 232 @SuppressWarnings("GoodTime") // b/122668874 233 @Override 234 public void recordLoadException(long loadTime) { 235 loadExceptionCount.increment(); 236 totalLoadTime.add(loadTime); 237 } 238 239 @Override 240 public void recordEviction() { 241 evictionCount.increment(); 242 } 243 244 @Override 245 public CacheStats snapshot() { 246 return new CacheStats( 247 negativeToMaxValue(hitCount.sum()), 248 negativeToMaxValue(missCount.sum()), 249 negativeToMaxValue(loadSuccessCount.sum()), 250 negativeToMaxValue(loadExceptionCount.sum()), 251 negativeToMaxValue(totalLoadTime.sum()), 252 negativeToMaxValue(evictionCount.sum())); 253 } 254 255 /** Returns {@code value}, if non-negative. Otherwise, returns {@link Long#MAX_VALUE}. */ 256 private static long negativeToMaxValue(long value) { 257 return (value >= 0) ? value : Long.MAX_VALUE; 258 } 259 260 /** Increments all counters by the values in {@code other}. */ 261 public void incrementBy(StatsCounter other) { 262 CacheStats otherStats = other.snapshot(); 263 hitCount.add(otherStats.hitCount()); 264 missCount.add(otherStats.missCount()); 265 loadSuccessCount.add(otherStats.loadSuccessCount()); 266 loadExceptionCount.add(otherStats.loadExceptionCount()); 267 totalLoadTime.add(otherStats.totalLoadTime()); 268 evictionCount.add(otherStats.evictionCount()); 269 } 270 } 271}