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.base.Function; 023 import com.google.common.base.Supplier; 024 025 import java.io.Serializable; 026 027 /** 028 * Computes or retrieves values, based on a key, for use in populating a {@code Cache}. 029 * 030 * @author Charles Fry 031 * @since 10.0 032 */ 033 @Beta 034 public abstract class CacheLoader<K, V> { 035 036 /** 037 * Returns a {@code CacheLoader} which creates values by applying a {@code Function} to the key. 038 */ 039 public static <K, V> CacheLoader<K, V> from(Function<K, V> function) { 040 return new FunctionToCacheLoader<K, V>(function); 041 } 042 043 private static final class FunctionToCacheLoader<K, V> 044 extends CacheLoader<K, V> implements Serializable { 045 private final Function<K, V> computingFunction; 046 047 public FunctionToCacheLoader(Function<K, V> computingFunction) { 048 this.computingFunction = checkNotNull(computingFunction); 049 } 050 051 @Override 052 public V load(K key) { 053 return computingFunction.apply(key); 054 } 055 056 private static final long serialVersionUID = 0; 057 } 058 059 /** 060 * Returns a {@code CacheLoader} which obtains values from a {@code Supplier} (independent of the 061 * key). 062 */ 063 public static <V> CacheLoader<Object, V> from(Supplier<V> supplier) { 064 return new SupplierToCacheLoader<V>(supplier); 065 } 066 067 private static final class SupplierToCacheLoader<V> 068 extends CacheLoader<Object, V> implements Serializable { 069 private final Supplier<V> computingSupplier; 070 071 public SupplierToCacheLoader(Supplier<V> computingSupplier) { 072 this.computingSupplier = checkNotNull(computingSupplier); 073 } 074 075 @Override 076 public V load(Object key) { 077 return computingSupplier.get(); 078 } 079 080 private static final long serialVersionUID = 0; 081 } 082 083 /** 084 * Computes or retrieves the value corresponding to {@code key}. 085 * 086 * @param key the key whose value should be loaded; will never be null 087 * @return the value associated with {@code key}; <b>may not be null</b> 088 */ 089 public abstract V load(K key) throws Exception; 090 091 // TODO(fry): loadAll 092 093 }