1 /* 2 * Copyright (C) 2011 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5 * in compliance with the License. You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software distributed under the License 10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11 * or implied. See the License for the specific language governing permissions and limitations under 12 * the License. 13 */ 14 15 package com.google.common.cache; 16 17 import com.google.common.annotations.GwtCompatible; 18 import com.google.common.collect.ImmutableMap; 19 import com.google.common.util.concurrent.ExecutionError; 20 import com.google.common.util.concurrent.UncheckedExecutionException; 21 import com.google.errorprone.annotations.CompatibleWith; 22 import java.util.Map; 23 import java.util.concurrent.Callable; 24 import java.util.concurrent.ConcurrentMap; 25 import java.util.concurrent.ExecutionException; 26 import org.checkerframework.checker.nullness.qual.Nullable; 27 28 /** 29 * A semi-persistent mapping from keys to values. Cache entries are manually added using {@link 30 * #get(Object, Callable)} or {@link #put(Object, Object)}, and are stored in the cache until either 31 * evicted or manually invalidated. The common way to build instances is using {@link CacheBuilder}. 32 * 33 * <p>Implementations of this interface are expected to be thread-safe, and can be safely accessed 34 * by multiple concurrent threads. 35 * 36 * @author Charles Fry 37 * @since 10.0 38 */ 39 @GwtCompatible 40 public interface Cache<K, V> { 41 42 /** 43 * Returns the value associated with {@code key} in this cache, or {@code null} if there is no 44 * cached value for {@code key}. 45 * 46 * @since 11.0 47 */ 48 @Nullable getIfPresent(@ompatibleWith"K") Object key)49 V getIfPresent(@CompatibleWith("K") Object key); 50 51 /** 52 * Returns the value associated with {@code key} in this cache, obtaining that value from {@code 53 * loader} if necessary. The method improves upon the conventional "if cached, return; otherwise 54 * create, cache and return" pattern. For further improvements, use {@link LoadingCache} and its 55 * {@link LoadingCache#get(Object) get(K)} method instead of this one. 56 * 57 * <p>Among the improvements that this method and {@code LoadingCache.get(K)} both provide are: 58 * 59 * <ul> 60 * <li>{@linkplain LoadingCache#get(Object) awaiting the result of a pending load} rather than 61 * starting a redundant one 62 * <li>eliminating the error-prone caching boilerplate 63 * <li>tracking load {@linkplain #stats statistics} 64 * </ul> 65 * 66 * <p>Among the further improvements that {@code LoadingCache} can provide but this method cannot: 67 * 68 * <ul> 69 * <li>consolidation of the loader logic to {@linkplain CacheBuilder#build(CacheLoader) a single 70 * authoritative location} 71 * <li>{@linkplain LoadingCache#refresh refreshing of entries}, including {@linkplain 72 * CacheBuilder#refreshAfterWrite automated refreshing} 73 * <li>{@linkplain LoadingCache#getAll bulk loading requests}, including {@linkplain 74 * CacheLoader#loadAll bulk loading implementations} 75 * </ul> 76 * 77 * <p><b>Warning:</b> For any given key, every {@code loader} used with it should compute the same 78 * value. Otherwise, a call that passes one {@code loader} may return the result of another call 79 * with a differently behaving {@code loader}. For example, a call that requests a short timeout 80 * for an RPC may wait for a similar call that requests a long timeout, or a call by an 81 * unprivileged user may return a resource accessible only to a privileged user making a similar 82 * call. To prevent this problem, create a key object that includes all values that affect the 83 * result of the query. Or use {@code LoadingCache.get(K)}, which lacks the ability to refer to 84 * state other than that in the key. 85 * 86 * <p><b>Warning:</b> as with {@link CacheLoader#load}, {@code loader} <b>must not</b> return 87 * {@code null}; it may either return a non-null value or throw an exception. 88 * 89 * <p>No observable state associated with this cache is modified until loading completes. 90 * 91 * @throws ExecutionException if a checked exception was thrown while loading the value 92 * @throws UncheckedExecutionException if an unchecked exception was thrown while loading the 93 * value 94 * @throws ExecutionError if an error was thrown while loading the value 95 * @since 11.0 96 */ get(K key, Callable<? extends V> loader)97 V get(K key, Callable<? extends V> loader) throws ExecutionException; 98 99 /** 100 * Returns a map of the values associated with {@code keys} in this cache. The returned map will 101 * only contain entries which are already present in the cache. 102 * 103 * @since 11.0 104 */ getAllPresent(Iterable<?> keys)105 ImmutableMap<K, V> getAllPresent(Iterable<?> keys); 106 107 /** 108 * Associates {@code value} with {@code key} in this cache. If the cache previously contained a 109 * value associated with {@code key}, the old value is replaced by {@code value}. 110 * 111 * <p>Prefer {@link #get(Object, Callable)} when using the conventional "if cached, return; 112 * otherwise create, cache and return" pattern. 113 * 114 * @since 11.0 115 */ put(K key, V value)116 void put(K key, V value); 117 118 /** 119 * Copies all of the mappings from the specified map to the cache. The effect of this call is 120 * equivalent to that of calling {@code put(k, v)} on this map once for each mapping from key 121 * {@code k} to value {@code v} in the specified map. The behavior of this operation is undefined 122 * if the specified map is modified while the operation is in progress. 123 * 124 * @since 12.0 125 */ putAll(Map<? extends K, ? extends V> m)126 void putAll(Map<? extends K, ? extends V> m); 127 128 /** Discards any cached value for key {@code key}. */ invalidate(@ompatibleWith"K") Object key)129 void invalidate(@CompatibleWith("K") Object key); 130 131 /** 132 * Discards any cached values for keys {@code keys}. 133 * 134 * @since 11.0 135 */ invalidateAll(Iterable<?> keys)136 void invalidateAll(Iterable<?> keys); 137 138 /** Discards all entries in the cache. */ invalidateAll()139 void invalidateAll(); 140 141 /** Returns the approximate number of entries in this cache. */ size()142 long size(); 143 144 /** 145 * Returns a current snapshot of this cache's cumulative statistics, or a set of default values if 146 * the cache is not recording statistics. All statistics begin at zero and never decrease over the 147 * lifetime of the cache. 148 * 149 * <p><b>Warning:</b> this cache may not be recording statistical data. For example, a cache 150 * created using {@link CacheBuilder} only does so if the {@link CacheBuilder#recordStats} method 151 * was called. If statistics are not being recorded, a {@code CacheStats} instance with zero for 152 * all values is returned. 153 * 154 */ stats()155 CacheStats stats(); 156 157 /** 158 * Returns a view of the entries stored in this cache as a thread-safe map. Modifications made to 159 * the map directly affect the cache. 160 * 161 * <p>Iterators from the returned map are at least <i>weakly consistent</i>: they are safe for 162 * concurrent use, but if the cache is modified (including by eviction) after the iterator is 163 * created, it is undefined which of the changes (if any) will be reflected in that iterator. 164 */ asMap()165 ConcurrentMap<K, V> asMap(); 166 167 /** 168 * Performs any pending maintenance operations needed by the cache. Exactly which activities are 169 * performed -- if any -- is implementation-dependent. 170 */ cleanUp()171 void cleanUp(); 172 } 173