• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 
15 package com.google.common.cache;
16 
17 import com.google.common.annotations.GwtCompatible;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.Maps;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.concurrent.Callable;
23 import java.util.concurrent.ConcurrentMap;
24 import java.util.concurrent.ExecutionException;
25 
26 /**
27  * This class provides a skeletal implementation of the {@code Cache} interface to minimize the
28  * effort required to implement this interface.
29  *
30  * <p>To implement a cache, the programmer needs only to extend this class and provide an
31  * implementation for the {@link #put} and {@link #getIfPresent} methods. {@link #getAllPresent} is
32  * implemented in terms of {@link #getIfPresent}; {@link #putAll} is implemented in terms of {@link
33  * #put}, {@link #invalidateAll(Iterable)} is implemented in terms of {@link #invalidate}. The
34  * method {@link #cleanUp} is a no-op. All other methods throw an {@link
35  * UnsupportedOperationException}.
36  *
37  * @author Charles Fry
38  * @since 10.0
39  */
40 @GwtCompatible
41 @ElementTypesAreNonnullByDefault
42 public abstract class AbstractCache<K, V> implements Cache<K, V> {
43 
44   /** Constructor for use by subclasses. */
AbstractCache()45   protected AbstractCache() {}
46 
47   /** @since 11.0 */
48   @Override
get(K key, Callable<? extends V> valueLoader)49   public V get(K key, Callable<? extends V> valueLoader) throws ExecutionException {
50     throw new UnsupportedOperationException();
51   }
52 
53   /**
54    * {@inheritDoc}
55    *
56    * <p>This implementation of {@code getAllPresent} lacks any insight into the internal cache data
57    * structure, and is thus forced to return the query keys instead of the cached keys. This is only
58    * possible with an unsafe cast which requires {@code keys} to actually be of type {@code K}.
59    *
60    * @since 11.0
61    */
62   /*
63    * <? extends Object> is mostly the same as <?> to plain Java. But to nullness checkers, they
64    * differ: <? extends Object> means "non-null types," while <?> means "all types."
65    */
66   @Override
getAllPresent(Iterable<? extends Object> keys)67   public ImmutableMap<K, V> getAllPresent(Iterable<? extends Object> keys) {
68     Map<K, V> result = Maps.newLinkedHashMap();
69     for (Object key : keys) {
70       if (!result.containsKey(key)) {
71         @SuppressWarnings("unchecked")
72         K castKey = (K) key;
73         V value = getIfPresent(key);
74         if (value != null) {
75           result.put(castKey, value);
76         }
77       }
78     }
79     return ImmutableMap.copyOf(result);
80   }
81 
82   /** @since 11.0 */
83   @Override
put(K key, V value)84   public void put(K key, V value) {
85     throw new UnsupportedOperationException();
86   }
87 
88   /** @since 12.0 */
89   @Override
putAll(Map<? extends K, ? extends V> m)90   public void putAll(Map<? extends K, ? extends V> m) {
91     for (Entry<? extends K, ? extends V> entry : m.entrySet()) {
92       put(entry.getKey(), entry.getValue());
93     }
94   }
95 
96   @Override
cleanUp()97   public void cleanUp() {}
98 
99   @Override
size()100   public long size() {
101     throw new UnsupportedOperationException();
102   }
103 
104   @Override
invalidate(Object key)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.
invalidateAll(Iterable<? extends Object> keys)112   public void invalidateAll(Iterable<? extends Object> keys) {
113     for (Object key : keys) {
114       invalidate(key);
115     }
116   }
117 
118   @Override
invalidateAll()119   public void invalidateAll() {
120     throw new UnsupportedOperationException();
121   }
122 
123   @Override
stats()124   public CacheStats stats() {
125     throw new UnsupportedOperationException();
126   }
127 
128   @Override
asMap()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      */
recordHits(int count)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      */
recordMisses(int count)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
recordLoadSuccess(long loadTime)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
recordLoadException(long loadTime)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      */
recordEviction()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      */
snapshot()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. */
SimpleStatsCounter()211     public SimpleStatsCounter() {}
212 
213     /** @since 11.0 */
214     @Override
recordHits(int count)215     public void recordHits(int count) {
216       hitCount.add(count);
217     }
218 
219     /** @since 11.0 */
220     @Override
recordMisses(int count)221     public void recordMisses(int count) {
222       missCount.add(count);
223     }
224 
225     @SuppressWarnings("GoodTime") // b/122668874
226     @Override
recordLoadSuccess(long loadTime)227     public void recordLoadSuccess(long loadTime) {
228       loadSuccessCount.increment();
229       totalLoadTime.add(loadTime);
230     }
231 
232     @SuppressWarnings("GoodTime") // b/122668874
233     @Override
recordLoadException(long loadTime)234     public void recordLoadException(long loadTime) {
235       loadExceptionCount.increment();
236       totalLoadTime.add(loadTime);
237     }
238 
239     @Override
recordEviction()240     public void recordEviction() {
241       evictionCount.increment();
242     }
243 
244     @Override
snapshot()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}. */
negativeToMaxValue(long 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}. */
incrementBy(StatsCounter 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 }
272