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.Beta;
022import com.google.common.annotations.GwtCompatible;
023import com.google.common.annotations.GwtIncompatible;
024import com.google.common.base.Function;
025import com.google.common.base.Supplier;
026import com.google.common.util.concurrent.Futures;
027import com.google.common.util.concurrent.ListenableFuture;
028
029import java.io.Serializable;
030import java.util.Map;
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: <pre>   {@code
039 *
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);}</pre>
046 *
047 * @author Charles Fry
048 * @since 10.0
049 */
050@GwtCompatible(emulated = true)
051public abstract class CacheLoader<K, V> {
052  /**
053   * Constructor for use by subclasses.
054   */
055  protected CacheLoader() {}
056
057  /**
058   * Computes or retrieves the value corresponding to {@code key}.
059   *
060   * @param key the non-null key whose value should be loaded
061   * @return the value associated with {@code key}; <b>must not be null</b>
062   * @throws Exception if unable to load the result
063   * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
064   *     treated like any other {@code Exception} in all respects except that, when it is caught,
065   *     the thread's interrupt status is set
066   */
067  public abstract V load(K key) throws Exception;
068
069  /**
070   * Computes or retrieves a replacement value corresponding to an already-cached {@code key}. This
071   * method is called when an existing cache entry is refreshed by
072   * {@link CacheBuilder#refreshAfterWrite}, or through a call to {@link LoadingCache#refresh}.
073   *
074   * <p>This implementation synchronously delegates to {@link #load}. It is recommended that it be
075   * overridden with an asynchronous implementation when using
076   * {@link CacheBuilder#refreshAfterWrite}.
077   *
078   * <p><b>Note:</b> <i>all exceptions thrown by this method will be logged and then swallowed</i>.
079   *
080   * @param key the non-null key whose value should be loaded
081   * @param oldValue the non-null old value corresponding to {@code key}
082   * @return the future new value associated with {@code key};
083   *     <b>must not be null, must not return null</b>
084   * @throws Exception if unable to reload the result
085   * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
086   *     treated like any other {@code Exception} in all respects except that, when it is caught,
087   *     the thread's interrupt status is set
088   * @since 11.0
089   */
090  @GwtIncompatible("Futures")
091  public ListenableFuture<V> reload(K key, V oldValue) throws Exception {
092    return Futures.immediateFuture(load(key));
093  }
094
095  /**
096   * Computes or retrieves the values corresponding to {@code keys}. This method is called by
097   * {@link LoadingCache#getAll}.
098   *
099   * <p>If the returned map doesn't contain all requested {@code keys} then the entries it does
100   * contain will be cached, but {@code getAll} will throw an exception. If the returned map
101   * contains extra keys not present in {@code keys} then all returned entries will be cached,
102   * but only the entries for {@code keys} will be returned from {@code getAll}.
103   *
104   * <p>This method should be overriden when bulk retrieval is significantly more efficient than
105   * many individual lookups. Note that {@link LoadingCache#getAll} will defer to individual calls
106   * to {@link LoadingCache#get} if this method is not overriden.
107   *
108   * @param keys the unique, non-null keys whose values should be loaded
109   * @return a map from each key in {@code keys} to the value associated with that key;
110   *     <b>may not contain null values</b>
111   * @throws Exception if unable to load the result
112   * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is
113   *     treated like any other {@code Exception} in all respects except that, when it is caught,
114   *     the thread's interrupt status is set
115   * @since 11.0
116   */
117  public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
118    // This will be caught by getAll(), causing it to fall back to multiple calls to
119    // LoadingCache.get
120    throw new UnsupportedLoadingOperationException();
121  }
122
123  /**
124   * Returns a cache loader based on an <i>existing</i> function instance. Note that there's no need
125   * to create a <i>new</i> function just to pass it in here; just subclass {@code CacheLoader} and
126   * implement {@link #load load} instead.
127   *
128   * @param function the function to be used for loading values; must never return {@code null}
129   * @return a cache loader that loads values by passing each key to {@code function}
130   */
131  @Beta
132  public static <K, V> CacheLoader<K, V> from(Function<K, V> function) {
133    return new FunctionToCacheLoader<K, V>(function);
134  }
135
136  private static final class FunctionToCacheLoader<K, V>
137      extends CacheLoader<K, V> implements Serializable {
138    private final Function<K, V> computingFunction;
139
140    public FunctionToCacheLoader(Function<K, V> computingFunction) {
141      this.computingFunction = checkNotNull(computingFunction);
142    }
143
144    @Override
145    public V load(K key) {
146      return computingFunction.apply(key);
147    }
148
149    private static final long serialVersionUID = 0;
150  }
151
152  /**
153   * Returns a cache loader based on an <i>existing</i> supplier instance. Note that there's no need
154   * to create a <i>new</i> supplier just to pass it in here; just subclass {@code CacheLoader} and
155   * implement {@link #load load} instead.
156   *
157   * @param supplier the supplier to be used for loading values; must never return {@code null}
158   * @return a cache loader that loads values by calling {@link Supplier#get}, irrespective of the
159   *     key
160   */
161  @Beta
162  public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) {
163    return new SupplierToCacheLoader<V>(supplier);
164  }
165
166  private static final class SupplierToCacheLoader<V>
167      extends CacheLoader<Object, V> implements Serializable {
168    private final Supplier<V> computingSupplier;
169
170    public SupplierToCacheLoader(Supplier<V> computingSupplier) {
171      this.computingSupplier = checkNotNull(computingSupplier);
172    }
173
174    @Override
175    public V load(Object key) {
176      return computingSupplier.get();
177    }
178
179    private static final long serialVersionUID = 0;
180  }
181
182  static final class UnsupportedLoadingOperationException extends UnsupportedOperationException {}
183
184  /**
185   * Thrown to indicate that an invalid response was returned from a call to {@link CacheLoader}.
186   *
187   * @since 11.0
188   */
189  public static final class InvalidCacheLoadException extends RuntimeException {
190    public InvalidCacheLoadException(String message) {
191      super(message);
192    }
193  }
194}