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