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