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)
060public abstract class CacheLoader<K, V> {
061  /** Constructor for use by subclasses. */
062  protected CacheLoader() {}
063
064  /**
065   * Computes or retrieves the value corresponding to {@code key}.
066   *
067   * @param key the non-null key whose value should be loaded
068   * @return the value associated with {@code key}; <b>must not be null</b>
069   * @throws Exception if unable to load the result
070   * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
071   *     treated like any other {@code Exception} in all respects except that, when it is caught,
072   *     the thread's interrupt status is set
073   */
074  public abstract V load(K key) throws Exception;
075
076  /**
077   * Computes or retrieves a replacement value corresponding to an already-cached {@code key}. This
078   * method is called when an existing cache entry is refreshed by {@link
079   * CacheBuilder#refreshAfterWrite}, or through a call to {@link LoadingCache#refresh}.
080   *
081   * <p>This implementation synchronously delegates to {@link #load}. It is recommended that it be
082   * overridden with an asynchronous implementation when using {@link
083   * CacheBuilder#refreshAfterWrite}.
084   *
085   * <p><b>Note:</b> <i>all exceptions thrown by this method will be logged and then swallowed</i>.
086   *
087   * @param key the non-null key whose value should be loaded
088   * @param oldValue the non-null old value corresponding to {@code key}
089   * @return the future new value associated with {@code key}; <b>must not be null, must not return
090   *     null</b>
091   * @throws Exception if unable to reload the result
092   * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
093   *     treated like any other {@code Exception} in all respects except that, when it is caught,
094   *     the thread's interrupt status is set
095   * @since 11.0
096   */
097  @GwtIncompatible // Futures
098  public ListenableFuture<V> reload(K key, V oldValue) throws Exception {
099    checkNotNull(key);
100    checkNotNull(oldValue);
101    return Futures.immediateFuture(load(key));
102  }
103
104  /**
105   * Computes or retrieves the values corresponding to {@code keys}. This method is called by {@link
106   * LoadingCache#getAll}.
107   *
108   * <p>If the returned map doesn't contain all requested {@code keys} then the entries it does
109   * contain will be cached, but {@code getAll} will throw an exception. If the returned map
110   * contains extra keys not present in {@code keys} then all returned entries will be cached, but
111   * only the entries for {@code keys} will be returned from {@code getAll}.
112   *
113   * <p>This method should be overridden when bulk retrieval is significantly more efficient than
114   * many individual lookups. Note that {@link LoadingCache#getAll} will defer to individual calls
115   * to {@link LoadingCache#get} if this method is not overridden.
116   *
117   * @param keys the unique, non-null keys whose values should be loaded
118   * @return a map from each key in {@code keys} to the value associated with that key; <b>may not
119   *     contain null values</b>
120   * @throws Exception if unable to load the result
121   * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
122   *     treated like any other {@code Exception} in all respects except that, when it is caught,
123   *     the thread's interrupt status is set
124   * @since 11.0
125   */
126  public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
127    // This will be caught by getAll(), causing it to fall back to multiple calls to
128    // LoadingCache.get
129    throw new UnsupportedLoadingOperationException();
130  }
131
132  /**
133   * Returns a cache loader that uses {@code function} to load keys, and without supporting either
134   * reloading or bulk loading. This is most useful when you can pass a lambda expression. Otherwise
135   * it is useful mostly when you already have an existing function instance.
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  @CheckReturnValue
141  public static <K, V> CacheLoader<K, V> from(Function<K, V> function) {
142    return new FunctionToCacheLoader<>(function);
143  }
144
145  /**
146   * Returns a cache loader based on an <i>existing</i> supplier instance. Note that there's no need
147   * to create a <i>new</i> supplier just to pass it in here; just subclass {@code CacheLoader} and
148   * implement {@link #load load} instead.
149   *
150   * @param supplier the supplier to be used for loading values; must never return {@code null}
151   * @return a cache loader that loads values by calling {@link Supplier#get}, irrespective of the
152   *     key
153   */
154  @CheckReturnValue
155  public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) {
156    return new SupplierToCacheLoader<V>(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  @CheckReturnValue
185  @GwtIncompatible // Executor + Futures
186  public static <K, V> CacheLoader<K, V> asyncReloading(
187      final CacheLoader<K, V> loader, final Executor executor) {
188    checkNotNull(loader);
189    checkNotNull(executor);
190    return new CacheLoader<K, V>() {
191      @Override
192      public V load(K key) throws Exception {
193        return loader.load(key);
194      }
195
196      @Override
197      public ListenableFuture<V> reload(final K key, final V oldValue) throws Exception {
198        ListenableFutureTask<V> task =
199            ListenableFutureTask.create(
200                new Callable<V>() {
201                  @Override
202                  public V call() throws Exception {
203                    return loader.reload(key, oldValue).get();
204                  }
205                });
206        executor.execute(task);
207        return task;
208      }
209
210      @Override
211      public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
212        return loader.loadAll(keys);
213      }
214    };
215  }
216
217  private static final class SupplierToCacheLoader<V> extends CacheLoader<Object, V>
218      implements Serializable {
219    private final Supplier<V> computingSupplier;
220
221    public SupplierToCacheLoader(Supplier<V> computingSupplier) {
222      this.computingSupplier = checkNotNull(computingSupplier);
223    }
224
225    @Override
226    public V load(Object key) {
227      checkNotNull(key);
228      return computingSupplier.get();
229    }
230
231    private static final long serialVersionUID = 0;
232  }
233
234  /**
235   * Exception thrown by {@code loadAll()} to indicate that it is not supported.
236   *
237   * @since 19.0
238   */
239  public static final class UnsupportedLoadingOperationException
240      extends UnsupportedOperationException {
241    // Package-private because this should only be thrown by loadAll() when it is not overridden.
242    // Cache implementors may want to catch it but should not need to be able to throw it.
243    UnsupportedLoadingOperationException() {}
244  }
245
246  /**
247   * Thrown to indicate that an invalid response was returned from a call to {@link CacheLoader}.
248   *
249   * @since 11.0
250   */
251  public static final class InvalidCacheLoadException extends RuntimeException {
252    public InvalidCacheLoadException(String message) {
253      super(message);
254    }
255  }
256}