Coverage Summary for Class: CacheLoader (com.google.common.cache)

Class Method, % Line, %
CacheLoader 0% (0/6) 0% (0/10)
CacheLoader$1 0% (0/4) 0% (0/7)
CacheLoader$1$1 0% (0/2) 0% (0/2)
CacheLoader$FunctionToCacheLoader 0% (0/2) 0% (0/3)
CacheLoader$InvalidCacheLoadException 0% (0/1) 0% (0/1)
CacheLoader$SupplierToCacheLoader 0% (0/2) 0% (0/4)
CacheLoader$UnsupportedLoadingOperationException 0% (0/1) 0% (0/1)
Total 0% (0/18) 0% (0/28)


1 /* 2  * Copyright (C) 2011 The Guava Authors 3  * 4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 5  * in compliance with the License. You may obtain a copy of the License at 6  * 7  * http://www.apache.org/licenses/LICENSE-2.0 8  * 9  * Unless required by applicable law or agreed to in writing, software distributed under the License 10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 11  * or implied. See the License for the specific language governing permissions and limitations under 12  * the License. 13  */ 14  15 package com.google.common.cache; 16  17 import static com.google.common.base.Preconditions.checkNotNull; 18  19 import com.google.common.annotations.GwtCompatible; 20 import com.google.common.annotations.GwtIncompatible; 21 import com.google.common.base.Function; 22 import com.google.common.base.Supplier; 23 import com.google.common.util.concurrent.Futures; 24 import com.google.common.util.concurrent.ListenableFuture; 25 import com.google.common.util.concurrent.ListenableFutureTask; 26 import com.google.errorprone.annotations.CheckReturnValue; 27 import java.io.Serializable; 28 import java.util.Map; 29 import java.util.concurrent.Callable; 30 import java.util.concurrent.Executor; 31  32 /** 33  * Computes or retrieves values, based on a key, for use in populating a {@link LoadingCache}. 34  * 35  * <p>Most implementations will only need to implement {@link #load}. Other methods may be 36  * overridden as desired. 37  * 38  * <p>Usage example: 39  * 40  * <pre>{@code 41  * CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() { 42  * public Graph load(Key key) throws AnyException { 43  * return createExpensiveGraph(key); 44  * } 45  * }; 46  * LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader); 47  * }</pre> 48  * 49  * <p>Since this example doesn't support reloading or bulk loading, it can also be specified much 50  * more simply: 51  * 52  * <pre>{@code 53  * CacheLoader<Key, Graph> loader = CacheLoader.from(key -> createExpensiveGraph(key)); 54  * }</pre> 55  * 56  * @author Charles Fry 57  * @since 10.0 58  */ 59 @GwtCompatible(emulated = true) 60 public abstract class CacheLoader<K, V> { 61  /** Constructor for use by subclasses. */ 62  protected CacheLoader() {} 63  64  /** 65  * Computes or retrieves the value corresponding to {@code key}. 66  * 67  * @param key the non-null key whose value should be loaded 68  * @return the value associated with {@code key}; <b>must not be null</b> 69  * @throws Exception if unable to load the result 70  * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is 71  * treated like any other {@code Exception} in all respects except that, when it is caught, 72  * the thread's interrupt status is set 73  */ 74  public abstract V load(K key) throws Exception; 75  76  /** 77  * Computes or retrieves a replacement value corresponding to an already-cached {@code key}. This 78  * method is called when an existing cache entry is refreshed by {@link 79  * CacheBuilder#refreshAfterWrite}, or through a call to {@link LoadingCache#refresh}. 80  * 81  * <p>This implementation synchronously delegates to {@link #load}. It is recommended that it be 82  * overridden with an asynchronous implementation when using {@link 83  * CacheBuilder#refreshAfterWrite}. 84  * 85  * <p><b>Note:</b> <i>all exceptions thrown by this method will be logged and then swallowed</i>. 86  * 87  * @param key the non-null key whose value should be loaded 88  * @param oldValue the non-null old value corresponding to {@code key} 89  * @return the future new value associated with {@code key}; <b>must not be null, must not return 90  * null</b> 91  * @throws Exception if unable to reload the result 92  * @throws InterruptedException if this method is interrupted. {@code InterruptedException} is 93  * treated like any other {@code Exception} in all respects except that, when it is caught, 94  * the thread's interrupt status is set 95  * @since 11.0 96  */ 97  @GwtIncompatible // Futures 98  public ListenableFuture<V> reload(K key, V oldValue) throws Exception { 99  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, without supporting either 134  * reloading or bulk loading. This allows creating a cache loader using a lambda expression. 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  @CheckReturnValue 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  * @param supplier the supplier to be used for loading values; must never return {@code null} 150  * @return a cache loader that loads values by calling {@link Supplier#get}, irrespective of the 151  * key 152  */ 153  @CheckReturnValue 154  public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) { 155  return new SupplierToCacheLoader<V>(supplier); 156  } 157  158  private static final class FunctionToCacheLoader<K, V> extends CacheLoader<K, V> 159  implements Serializable { 160  private final Function<K, V> computingFunction; 161  162  public FunctionToCacheLoader(Function<K, V> computingFunction) { 163  this.computingFunction = checkNotNull(computingFunction); 164  } 165  166  @Override 167  public V load(K key) { 168  return computingFunction.apply(checkNotNull(key)); 169  } 170  171  private static final long serialVersionUID = 0; 172  } 173  174  /** 175  * Returns a {@code CacheLoader} which wraps {@code loader}, executing calls to {@link 176  * CacheLoader#reload} using {@code executor}. 177  * 178  * <p>This method is useful only when {@code loader.reload} has a synchronous implementation, such 179  * as {@linkplain #reload the default implementation}. 180  * 181  * @since 17.0 182  */ 183  @CheckReturnValue 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) throws Exception { 197  ListenableFutureTask<V> task = 198  ListenableFutureTask.create( 199  new Callable<V>() { 200  @Override 201  public V call() throws Exception { 202  return loader.reload(key, oldValue).get(); 203  } 204  }); 205  executor.execute(task); 206  return task; 207  } 208  209  @Override 210  public Map<K, V> loadAll(Iterable<? extends K> keys) throws Exception { 211  return loader.loadAll(keys); 212  } 213  }; 214  } 215  216  private static final class SupplierToCacheLoader<V> extends CacheLoader<Object, V> 217  implements Serializable { 218  private final Supplier<V> computingSupplier; 219  220  public SupplierToCacheLoader(Supplier<V> computingSupplier) { 221  this.computingSupplier = checkNotNull(computingSupplier); 222  } 223  224  @Override 225  public V load(Object key) { 226  checkNotNull(key); 227  return computingSupplier.get(); 228  } 229  230  private static final long serialVersionUID = 0; 231  } 232  233  /** 234  * Exception thrown by {@code loadAll()} to indicate that it is not supported. 235  * 236  * @since 19.0 237  */ 238  public static final class UnsupportedLoadingOperationException 239  extends UnsupportedOperationException { 240  // Package-private because this should only be thrown by loadAll() when it is not overridden. 241  // Cache implementors may want to catch it but should not need to be able to throw it. 242  UnsupportedLoadingOperationException() {} 243  } 244  245  /** 246  * Thrown to indicate that an invalid response was returned from a call to {@link CacheLoader}. 247  * 248  * @since 11.0 249  */ 250  public static final class InvalidCacheLoadException extends RuntimeException { 251  public InvalidCacheLoadException(String message) { 252  super(message); 253  } 254  } 255 }