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