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