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    
017    package com.google.common.cache;
018    
019    import static com.google.common.base.Preconditions.checkNotNull;
020    
021    import com.google.common.annotations.Beta;
022    import com.google.common.annotations.GwtCompatible;
023    import com.google.common.annotations.GwtIncompatible;
024    import com.google.common.base.Function;
025    import com.google.common.base.Supplier;
026    import com.google.common.util.concurrent.Futures;
027    import com.google.common.util.concurrent.ListenableFuture;
028    
029    import java.io.Serializable;
030    import java.util.Map;
031    
032    /**
033     * Computes or retrieves values, based on a key, for use in populating a {@code Cache}.
034     *
035     * <p>Most implementations will only need to implement {@link #load}. Other methods may be
036     * overridden as desired.
037     *
038     * @author Charles Fry
039     * @since 10.0
040     */
041    @Beta
042    @GwtCompatible(emulated = true)
043    public abstract class CacheLoader<K, V> {
044      /**
045       * Constructor for use by subclasses.
046       */
047      protected CacheLoader() {}
048    
049      /**
050       * Computes or retrieves the value corresponding to {@code key}.
051       *
052       * @param key the non-null key whose value should be loaded
053       * @return the value associated with {@code key}; <b>must not be null</b>
054       */
055      public abstract V load(K key) throws Exception;
056    
057      /**
058       * Computes or retrieves a replacement value corresponding to an already-cached {@code key}. This
059       * method is called when an existing cache entry is refreshed by
060       * {@link CacheBuilder#refreshAfterWrite}, or through a call to {@link Cache#refresh}.
061       *
062       * <p>This implementation synchronously delegates to {@link #load}. It is recommended that it be
063       * overridden with an asynchronous implementation when using
064       * {@link CacheBuilder#refreshAfterWrite}.
065       *
066       * <p><b>Note:</b> <i>all exceptions thrown by this method will be logged and then swallowed</i>.
067       *
068       * @param key the non-null key whose value should be loaded
069       * @param oldValue the non-null old value corresponding to {@code key}
070       * @return the future new value associated with {@code key};
071       *     <b>must not be null, must not return null</b>
072       * @since 11.0
073       */
074      @GwtIncompatible("Futures")
075      public ListenableFuture<V> reload(K key, V oldValue) throws Exception {
076        return Futures.immediateFuture(load(key));
077      }
078    
079      /**
080       * Computes or retrieves the values corresponding to {@code keys}. This method is called by
081       * {@link Cache#getAll}.
082       *
083       * <p>If the returned map doesn't contain all requested {@code keys} then the entries it does
084       * contain will be cached, but {@code getAll} will throw an exception. If the returned map
085       * contains extra keys not present in {@code keys} then all returned entries will be cached,
086       * but only the entries for {@code keys} will be returned from {@code getAll}.
087       *
088       * <p>This method should be overriden when bulk retrieval is significantly more efficient than
089       * many individual lookups. Note that {@link Cache#getAll} will defer to individual calls to
090       * {@link Cache#get} if this method is not overriden.
091       *
092       * @param keys the unique, non-null keys whose values should be loaded
093       * @return a map from each key in {@code keys} to the value associated with that key;
094       *     <b>may not contain null values</b>
095       * @since 11.0
096       */
097      public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception {
098        // This will be caught by getAll(), causing it to fall back to multiple calls to Cache.get
099        throw new UnsupportedLoadingOperationException();
100      }
101    
102      /**
103       * Returns a {@code CacheLoader} which creates values by applying a {@code Function} to the key.
104       */
105      public static <K, V> CacheLoader<K, V> from(Function<K, V> function) {
106        return new FunctionToCacheLoader<K, V>(function);
107      }
108    
109      private static final class FunctionToCacheLoader<K, V>
110          extends CacheLoader<K, V> implements Serializable {
111        private final Function<K, V> computingFunction;
112    
113        public FunctionToCacheLoader(Function<K, V> computingFunction) {
114          this.computingFunction = checkNotNull(computingFunction);
115        }
116    
117        @Override
118        public V load(K key) {
119          return computingFunction.apply(key);
120        }
121    
122        private static final long serialVersionUID = 0;
123      }
124    
125      /**
126       * Returns a {@code CacheLoader} which obtains values from a {@code Supplier} (independent of the
127       * key).
128       */
129      public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) {
130        return new SupplierToCacheLoader<V>(supplier);
131      }
132    
133      private static final class SupplierToCacheLoader<V>
134          extends CacheLoader<Object, V> implements Serializable {
135        private final Supplier<V> computingSupplier;
136    
137        public SupplierToCacheLoader(Supplier<V> computingSupplier) {
138          this.computingSupplier = checkNotNull(computingSupplier);
139        }
140    
141        @Override
142        public V load(Object key) {
143          return computingSupplier.get();
144        }
145    
146        private static final long serialVersionUID = 0;
147      }
148    
149      static final class UnsupportedLoadingOperationException extends UnsupportedOperationException {}
150    
151      /**
152       * Thrown to indicate that an invalid response was returned from a call to {@link CacheLoader}.
153       *
154       * @since 11.0
155       */
156      public static final class InvalidCacheLoadException extends RuntimeException {
157        public InvalidCacheLoadException(String message) {
158          super(message);
159        }
160      }
161    }