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 static com.google.common.base.Preconditions.checkNotNull; 018 019import com.google.common.annotations.GwtCompatible; 020import com.google.common.annotations.GwtIncompatible; 021import com.google.common.base.Function; 022import com.google.common.base.Supplier; 023import com.google.common.util.concurrent.Futures; 024import com.google.common.util.concurrent.ListenableFuture; 025import com.google.common.util.concurrent.ListenableFutureTask; 026import com.google.errorprone.annotations.CheckReturnValue; 027import java.io.Serializable; 028import java.util.Map; 029import java.util.concurrent.Callable; 030import java.util.concurrent.Executor; 031 032/** 033 * Computes or retrieves values, based on a key, for use in populating a {@link LoadingCache}. 034 * 035 * <p>Most implementations will only need to implement {@link #load}. Other methods may be 036 * overridden as desired. 037 * 038 * <p>Usage example: 039 * 040 * <pre>{@code 041 * CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() { 042 * public Graph load(Key key) throws AnyException { 043 * return createExpensiveGraph(key); 044 * } 045 * }; 046 * LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader); 047 * }</pre> 048 * 049 * <p>Since this example doesn't support reloading or bulk loading, if you're able to use lambda 050 * expressions it can be specified even more easily: 051 * 052 * <pre>{@code 053 * CacheLoader<Key, Graph> loader = CacheLoader.from(key -> createExpensiveGraph(key)); 054 * }</pre> 055 * 056 * @author Charles Fry 057 * @since 10.0 058 */ 059@GwtCompatible(emulated = true) 060@ElementTypesAreNonnullByDefault 061public abstract class CacheLoader<K, V> { 062 /** Constructor for use by subclasses. */ 063 protected CacheLoader() {} 064 065 /** 066 * Computes or retrieves the value corresponding to {@code key}. 067 * 068 * @param key the non-null key whose value should be loaded 069 * @return the value associated with {@code key}; <b>must not be null</b> 070 * @throws Exception if unable to load the result 071 * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is 072 * treated like any other {@code Exception} in all respects except that, when it is caught, 073 * the thread's interrupt status is set 074 */ 075 public abstract V load(K key) throws Exception; 076 077 /** 078 * Computes or retrieves a replacement value corresponding to an already-cached {@code key}. This 079 * method is called when an existing cache entry is refreshed by {@link 080 * CacheBuilder#refreshAfterWrite}, or through a call to {@link LoadingCache#refresh}. 081 * 082 * <p>This implementation synchronously delegates to {@link #load}. It is recommended that it be 083 * overridden with an asynchronous implementation when using {@link 084 * CacheBuilder#refreshAfterWrite}. 085 * 086 * <p><b>Note:</b> <i>all exceptions thrown by this method will be logged and then swallowed</i>. 087 * 088 * @param key the non-null key whose value should be loaded 089 * @param oldValue the non-null old value corresponding to {@code key} 090 * @return the future new value associated with {@code key}; <b>must not be null, must not return 091 * null</b> 092 * @throws Exception if unable to reload the result 093 * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is 094 * treated like any other {@code Exception} in all respects except that, when it is caught, 095 * the thread's interrupt status is set 096 * @since 11.0 097 */ 098 @GwtIncompatible // Futures 099 public ListenableFuture<V> reload(K key, V oldValue) throws Exception { 100 checkNotNull(key); 101 checkNotNull(oldValue); 102 return Futures.immediateFuture(load(key)); 103 } 104 105 /** 106 * Computes or retrieves the values corresponding to {@code keys}. This method is called by {@link 107 * LoadingCache#getAll}. 108 * 109 * <p>If the returned map doesn't contain all requested {@code keys} then the entries it does 110 * contain will be cached, but {@code getAll} will throw an exception. If the returned map 111 * contains extra keys not present in {@code keys} then all returned entries will be cached, but 112 * only the entries for {@code keys} will be returned from {@code getAll}. 113 * 114 * <p>This method should be overridden when bulk retrieval is significantly more efficient than 115 * many individual lookups. Note that {@link LoadingCache#getAll} will defer to individual calls 116 * to {@link LoadingCache#get} if this method is not overridden. 117 * 118 * @param keys the unique, non-null keys whose values should be loaded 119 * @return a map from each key in {@code keys} to the value associated with that key; <b>may not 120 * contain null values</b> 121 * @throws Exception if unable to load the result 122 * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is 123 * treated like any other {@code Exception} in all respects except that, when it is caught, 124 * the thread's interrupt status is set 125 * @since 11.0 126 */ 127 public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception { 128 // This will be caught by getAll(), causing it to fall back to multiple calls to 129 // LoadingCache.get 130 throw new UnsupportedLoadingOperationException(); 131 } 132 133 /** 134 * Returns a cache loader that uses {@code function} to load keys, and without supporting either 135 * reloading or bulk loading. This is most useful when you can pass a lambda expression. Otherwise 136 * it is useful mostly when you already have an existing function instance. 137 * 138 * @param function the function to be used for loading values; must never return {@code null} 139 * @return a cache loader that loads values by passing each key to {@code function} 140 */ 141 @CheckReturnValue 142 public static <K, V> CacheLoader<K, V> from(Function<K, V> function) { 143 return new FunctionToCacheLoader<>(function); 144 } 145 146 /** 147 * Returns a cache loader based on an <i>existing</i> supplier instance. Note that there's no need 148 * to create a <i>new</i> supplier just to pass it in here; just subclass {@code CacheLoader} and 149 * implement {@link #load load} instead. 150 * 151 * @param supplier the supplier to be used for loading values; must never return {@code null} 152 * @return a cache loader that loads values by calling {@link Supplier#get}, irrespective of the 153 * key 154 */ 155 @CheckReturnValue 156 public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) { 157 return new SupplierToCacheLoader<V>(supplier); 158 } 159 160 private static final class FunctionToCacheLoader<K, V> extends CacheLoader<K, V> 161 implements Serializable { 162 private final Function<K, V> computingFunction; 163 164 public FunctionToCacheLoader(Function<K, V> computingFunction) { 165 this.computingFunction = checkNotNull(computingFunction); 166 } 167 168 @Override 169 public V load(K key) { 170 return computingFunction.apply(checkNotNull(key)); 171 } 172 173 private static final long serialVersionUID = 0; 174 } 175 176 /** 177 * Returns a {@code CacheLoader} which wraps {@code loader}, executing calls to {@link 178 * CacheLoader#reload} using {@code executor}. 179 * 180 * <p>This method is useful only when {@code loader.reload} has a synchronous implementation, such 181 * as {@linkplain #reload the default implementation}. 182 * 183 * @since 17.0 184 */ 185 @CheckReturnValue 186 @GwtIncompatible // Executor + Futures 187 public static <K, V> CacheLoader<K, V> asyncReloading( 188 final CacheLoader<K, V> loader, final Executor executor) { 189 checkNotNull(loader); 190 checkNotNull(executor); 191 return new CacheLoader<K, V>() { 192 @Override 193 public V load(K key) throws Exception { 194 return loader.load(key); 195 } 196 197 @Override 198 public ListenableFuture<V> reload(final K key, final V oldValue) throws Exception { 199 ListenableFutureTask<V> task = 200 ListenableFutureTask.create( 201 new Callable<V>() { 202 @Override 203 public V call() throws Exception { 204 return loader.reload(key, oldValue).get(); 205 } 206 }); 207 executor.execute(task); 208 return task; 209 } 210 211 @Override 212 public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception { 213 return loader.loadAll(keys); 214 } 215 }; 216 } 217 218 private static final class SupplierToCacheLoader<V> extends CacheLoader<Object, V> 219 implements Serializable { 220 private final Supplier<V> computingSupplier; 221 222 public SupplierToCacheLoader(Supplier<V> computingSupplier) { 223 this.computingSupplier = checkNotNull(computingSupplier); 224 } 225 226 @Override 227 public V load(Object key) { 228 checkNotNull(key); 229 return computingSupplier.get(); 230 } 231 232 private static final long serialVersionUID = 0; 233 } 234 235 /** 236 * Exception thrown by {@code loadAll()} to indicate that it is not supported. 237 * 238 * @since 19.0 239 */ 240 public static final class UnsupportedLoadingOperationException 241 extends UnsupportedOperationException { 242 // Package-private because this should only be thrown by loadAll() when it is not overridden. 243 // Cache implementors may want to catch it but should not need to be able to throw it. 244 UnsupportedLoadingOperationException() {} 245 } 246 247 /** 248 * Thrown to indicate that an invalid response was returned from a call to {@link CacheLoader}. 249 * 250 * @since 11.0 251 */ 252 public static final class InvalidCacheLoadException extends RuntimeException { 253 public InvalidCacheLoadException(String message) { 254 super(message); 255 } 256 } 257}