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