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