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.base.Function;
019import com.google.common.collect.ImmutableMap;
020import com.google.common.util.concurrent.ExecutionError;
021import com.google.common.util.concurrent.UncheckedExecutionException;
022import com.google.errorprone.annotations.CanIgnoreReturnValue;
023import java.util.concurrent.ConcurrentMap;
024import java.util.concurrent.ExecutionException;
025
026/**
027 * A semi-persistent mapping from keys to values. Values are automatically loaded by the cache, and
028 * are stored in the cache until either evicted or manually invalidated. The common way to build
029 * instances is using {@link CacheBuilder}.
030 *
031 * <p>Implementations of this interface are expected to be thread-safe, and can be safely accessed
032 * by multiple concurrent threads.
033 *
034 * <p>When evaluated as a {@link Function}, a cache yields the same result as invoking {@link
035 * #getUnchecked}.
036 *
037 * @param <K> the type of the cache's keys, which are not permitted to be null
038 * @param <V> the type of the cache's values, which are not permitted to be null
039 * @author Charles Fry
040 * @since 11.0
041 */
042@GwtCompatible
043@ElementTypesAreNonnullByDefault
044public interface LoadingCache<K, V> extends Cache<K, V>, Function<K, V> {
045
046  /**
047   * Returns the value associated with {@code key} in this cache, first loading that value if
048   * necessary. No observable state associated with this cache is modified until loading completes.
049   *
050   * <p>If another call to {@link #get} or {@link #getUnchecked} is currently loading the value for
051   * {@code key}, simply waits for that thread to finish and returns its loaded value. Note that
052   * multiple threads can concurrently load values for distinct keys.
053   *
054   * <p>Caches loaded by a {@link CacheLoader} will call {@link CacheLoader#load} to load new values
055   * into the cache. Newly loaded values are added to the cache using {@code
056   * Cache.asMap().putIfAbsent} after loading has completed; if another value was associated with
057   * {@code key} while the new value was loading then a removal notification will be sent for the
058   * new value.
059   *
060   * <p>If the cache loader associated with this cache is known not to throw checked exceptions,
061   * then prefer {@link #getUnchecked} over this method.
062   *
063   * @throws ExecutionException if a checked exception was thrown while loading the value. ({@code
064   *     ExecutionException} is thrown <a
065   *     href="https://github.com/google/guava/wiki/CachesExplained#interruption">even if
066   *     computation was interrupted by an {@code InterruptedException}</a>.)
067   * @throws UncheckedExecutionException if an unchecked exception was thrown while loading the
068   *     value
069   * @throws ExecutionError if an error was thrown while loading the value
070   */
071  @CanIgnoreReturnValue // TODO(b/27479612): consider removing this?
072  V get(K key) throws ExecutionException;
073
074  /**
075   * Returns the value associated with {@code key} in this cache, first loading that value if
076   * necessary. No observable state associated with this cache is modified until loading completes.
077   * Unlike {@link #get}, this method does not throw a checked exception, and thus should only be
078   * used in situations where checked exceptions are not thrown by the cache loader.
079   *
080   * <p>If another call to {@link #get} or {@link #getUnchecked} is currently loading the value for
081   * {@code key}, simply waits for that thread to finish and returns its loaded value. Note that
082   * multiple threads can concurrently load values for distinct keys.
083   *
084   * <p>Caches loaded by a {@link CacheLoader} will call {@link CacheLoader#load} to load new values
085   * into the cache. Newly loaded values are added to the cache using {@code
086   * Cache.asMap().putIfAbsent} after loading has completed; if another value was associated with
087   * {@code key} while the new value was loading then a removal notification will be sent for the
088   * new value.
089   *
090   * <p><b>Warning:</b> this method silently converts checked exceptions to unchecked exceptions,
091   * and should not be used with cache loaders which throw checked exceptions. In such cases use
092   * {@link #get} instead.
093   *
094   * @throws UncheckedExecutionException if an exception was thrown while loading the value. (As
095   *     explained in the last paragraph above, this should be an unchecked exception only.)
096   * @throws ExecutionError if an error was thrown while loading the value
097   */
098  @CanIgnoreReturnValue // TODO(b/27479612): consider removing this?
099  V getUnchecked(K key);
100
101  /**
102   * Returns a map of the values associated with {@code keys}, creating or retrieving those values
103   * if necessary. The returned map contains entries that were already cached, combined with newly
104   * loaded entries; it will never contain null keys or values.
105   *
106   * <p>Caches loaded by a {@link CacheLoader} will issue a single request to {@link
107   * CacheLoader#loadAll} for all keys which are not already present in the cache. All entries
108   * returned by {@link CacheLoader#loadAll} will be stored in the cache, over-writing any
109   * previously cached values. This method will throw an exception if {@link CacheLoader#loadAll}
110   * returns {@code null}, returns a map containing null keys or values, or fails to return an entry
111   * for each requested key.
112   *
113   * <p>Note that duplicate elements in {@code keys}, as determined by {@link Object#equals}, will
114   * be ignored.
115   *
116   * @throws ExecutionException if a checked exception was thrown while loading the value. ({@code
117   *     ExecutionException} is thrown <a
118   *     href="https://github.com/google/guava/wiki/CachesExplained#interruption">even if
119   *     computation was interrupted by an {@code InterruptedException}</a>.)
120   * @throws UncheckedExecutionException if an unchecked exception was thrown while loading the
121   *     values
122   * @throws ExecutionError if an error was thrown while loading the values
123   * @since 11.0
124   */
125  @CanIgnoreReturnValue // TODO(b/27479612): consider removing this
126  ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException;
127
128  /**
129   * @deprecated Provided to satisfy the {@code Function} interface; use {@link #get} or {@link
130   *     #getUnchecked} instead.
131   * @throws UncheckedExecutionException if an exception was thrown while loading the value. (As
132   *     described in the documentation for {@link #getUnchecked}, {@code LoadingCache} should be
133   *     used as a {@code Function} only with cache loaders that throw only unchecked exceptions.)
134   */
135  @Deprecated
136  @Override
137  V apply(K key);
138
139  /**
140   * Loads a new value for {@code key}, possibly asynchronously. While the new value is loading the
141   * previous value (if any) will continue to be returned by {@code get(key)} unless it is evicted.
142   * If the new value is loaded successfully it will replace the previous value in the cache; if an
143   * exception is thrown while refreshing the previous value will remain, <i>and the exception will
144   * be logged (using {@link java.util.logging.Logger}) and swallowed</i>.
145   *
146   * <p>Caches loaded by a {@link CacheLoader} will call {@link CacheLoader#reload} if the cache
147   * currently contains a value for {@code key}, and {@link CacheLoader#load} otherwise. Loading is
148   * asynchronous only if {@link CacheLoader#reload} was overridden with an asynchronous
149   * implementation.
150   *
151   * <p>Returns without doing anything if another thread is currently loading the value for {@code
152   * key}. If the cache loader associated with this cache performs refresh asynchronously then this
153   * method may return before refresh completes.
154   *
155   * @since 11.0
156   */
157  void refresh(K key);
158
159  /**
160   * {@inheritDoc}
161   *
162   * <p><b>Note that although the view <i>is</i> modifiable, no method on the returned map will ever
163   * cause entries to be automatically loaded.</b>
164   */
165  @Override
166  ConcurrentMap<K, V> asMap();
167}