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.util.concurrent.ExecutionError;
020import com.google.common.util.concurrent.UncheckedExecutionException;
021import com.google.errorprone.annotations.CompatibleWith;
022import com.google.errorprone.annotations.DoNotMock;
023import java.util.Map;
024import java.util.concurrent.Callable;
025import java.util.concurrent.ConcurrentMap;
026import java.util.concurrent.ExecutionException;
027import org.checkerframework.checker.nullness.compatqual.NullableDecl;
028
029/**
030 * A semi-persistent mapping from keys to values. Cache entries are manually added using {@link
031 * #get(Object, Callable)} or {@link #put(Object, Object)}, and are stored in the cache until either
032 * evicted or manually invalidated. The common way to build instances is using {@link CacheBuilder}.
033 *
034 * <p>Implementations of this interface are expected to be thread-safe, and can be safely accessed
035 * by multiple concurrent threads.
036 *
037 * @author Charles Fry
038 * @since 10.0
039 */
040@DoNotMock("Use CacheBuilder.newBuilder().build()")
041@GwtCompatible
042public interface Cache<K, V> {
043
044  /**
045   * Returns the value associated with {@code key} in this cache, or {@code null} if there is no
046   * cached value for {@code key}.
047   *
048   * @since 11.0
049   */
050  @NullableDecl
051  V getIfPresent(@CompatibleWith("K") Object key);
052
053  /**
054   * Returns the value associated with {@code key} in this cache, obtaining that value from {@code
055   * loader} if necessary. The method improves upon the conventional "if cached, return; otherwise
056   * create, cache and return" pattern. For further improvements, use {@link LoadingCache} and its
057   * {@link LoadingCache#get(Object) get(K)} method instead of this one.
058   *
059   * <p>Among the improvements that this method and {@code LoadingCache.get(K)} both provide are:
060   *
061   * <ul>
062   *   <li>{@linkplain LoadingCache#get(Object) awaiting the result of a pending load} rather than
063   *       starting a redundant one
064   *   <li>eliminating the error-prone caching boilerplate
065   *   <li>tracking load {@linkplain #stats statistics}
066   * </ul>
067   *
068   * <p>Among the further improvements that {@code LoadingCache} can provide but this method cannot:
069   *
070   * <ul>
071   *   <li>consolidation of the loader logic to {@linkplain CacheBuilder#build(CacheLoader) a single
072   *       authoritative location}
073   *   <li>{@linkplain LoadingCache#refresh refreshing of entries}, including {@linkplain
074   *       CacheBuilder#refreshAfterWrite automated refreshing}
075   *   <li>{@linkplain LoadingCache#getAll bulk loading requests}, including {@linkplain
076   *       CacheLoader#loadAll bulk loading implementations}
077   * </ul>
078   *
079   * <p><b>Warning:</b> For any given key, every {@code loader} used with it should compute the same
080   * value. Otherwise, a call that passes one {@code loader} may return the result of another call
081   * with a differently behaving {@code loader}. For example, a call that requests a short timeout
082   * for an RPC may wait for a similar call that requests a long timeout, or a call by an
083   * unprivileged user may return a resource accessible only to a privileged user making a similar
084   * call. To prevent this problem, create a key object that includes all values that affect the
085   * result of the query. Or use {@code LoadingCache.get(K)}, which lacks the ability to refer to
086   * state other than that in the key.
087   *
088   * <p><b>Warning:</b> as with {@link CacheLoader#load}, {@code loader} <b>must not</b> return
089   * {@code null}; it may either return a non-null value or throw an exception.
090   *
091   * <p>No observable state associated with this cache is modified until loading completes.
092   *
093   * @throws ExecutionException if a checked exception was thrown while loading the value
094   * @throws UncheckedExecutionException if an unchecked exception was thrown while loading the
095   *     value
096   * @throws ExecutionError if an error was thrown while loading the value
097   * @since 11.0
098   */
099  V get(K key, Callable<? extends V> loader) throws ExecutionException;
100
101  /**
102   * Returns a map of the values associated with {@code keys} in this cache. The returned map will
103   * only contain entries which are already present in the cache.
104   *
105   * @since 11.0
106   */
107  ImmutableMap<K, V> getAllPresent(Iterable<?> keys);
108
109  /**
110   * Associates {@code value} with {@code key} in this cache. If the cache previously contained a
111   * value associated with {@code key}, the old value is replaced by {@code value}.
112   *
113   * <p>Prefer {@link #get(Object, Callable)} when using the conventional "if cached, return;
114   * otherwise create, cache and return" pattern.
115   *
116   * @since 11.0
117   */
118  void put(K key, V value);
119
120  /**
121   * Copies all of the mappings from the specified map to the cache. The effect of this call is
122   * equivalent to that of calling {@code put(k, v)} on this map once for each mapping from key
123   * {@code k} to value {@code v} in the specified map. The behavior of this operation is undefined
124   * if the specified map is modified while the operation is in progress.
125   *
126   * @since 12.0
127   */
128  void putAll(Map<? extends K, ? extends V> m);
129
130  /** Discards any cached value for key {@code key}. */
131  void invalidate(@CompatibleWith("K") Object key);
132
133  /**
134   * Discards any cached values for keys {@code keys}.
135   *
136   * @since 11.0
137   */
138  void invalidateAll(Iterable<?> keys);
139
140  /** Discards all entries in the cache. */
141  void invalidateAll();
142
143  /** Returns the approximate number of entries in this cache. */
144  long size();
145
146  /**
147   * Returns a current snapshot of this cache's cumulative statistics, or a set of default values if
148   * the cache is not recording statistics. All statistics begin at zero and never decrease over the
149   * lifetime of the cache.
150   *
151   * <p><b>Warning:</b> this cache may not be recording statistical data. For example, a cache
152   * created using {@link CacheBuilder} only does so if the {@link CacheBuilder#recordStats} method
153   * was called. If statistics are not being recorded, a {@code CacheStats} instance with zero for
154   * all values is returned.
155   *
156   */
157  CacheStats stats();
158
159  /**
160   * Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to
161   * the map directly affect the cache.
162   *
163   * <p>Iterators from the returned map are at least <i>weakly consistent</i>: they are safe for
164   * concurrent use, but if the cache is modified (including by eviction) after the iterator is
165   * created, it is undefined which of the changes (if any) will be reflected in that iterator.
166   *
167   * <p><b>Warning to users of Java 8+:</b> do not call any of the new <i>default methods</i> that
168   * have been newly added to {@link ConcurrentMap}! These are marked with "Since: 1.8" in the
169   * {@code ConcurrentMap} documentation. They will not function correctly and it is impossible for
170   * Guava to fix them until Guava is ready to <i>require</i> Java 8 for all users.
171   */
172  ConcurrentMap<K, V> asMap();
173
174  /**
175   * Performs any pending maintenance operations needed by the cache. Exactly which activities are
176   * performed -- if any -- is implementation-dependent.
177   */
178  void cleanUp();
179}