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