1 /* 2 * Copyright (C) 2011 The Guava Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.google.common.cache; 18 19 import com.google.common.annotations.Beta; 20 import com.google.common.collect.ImmutableMap; 21 import com.google.common.collect.Maps; 22 import com.google.common.util.concurrent.UncheckedExecutionException; 23 24 import java.util.Map; 25 import java.util.concurrent.Callable; 26 import java.util.concurrent.ExecutionException; 27 28 /** 29 * This class provides a skeletal implementation of the {@code Cache} interface to minimize the 30 * effort required to implement this interface. 31 * 32 * <p>To implement a cache, the programmer needs only to extend this class and provide an 33 * implementation for the {@link #get} and {@link #getIfPresent} methods. {@link #getUnchecked}, 34 * {@link #get(K, Callable)}, and {@link #getAll} are implemented in terms of {@code get}; 35 * {@link #getAllPresent} is implemented in terms of {@code get}; {@link #invalidateAll(Iterable)} 36 * is implemented in terms of {@link #invalidate}. The method {@link #cleanUp} is a no-op. All other 37 * methods throw an {@link UnsupportedOperationException}. 38 * 39 * @author Charles Fry 40 * @since 11.0 41 */ 42 @Beta 43 public abstract class AbstractLoadingCache<K, V> 44 extends AbstractCache<K, V> implements LoadingCache<K, V> { 45 46 /** Constructor for use by subclasses. */ AbstractLoadingCache()47 protected AbstractLoadingCache() {} 48 49 @Override getUnchecked(K key)50 public V getUnchecked(K key) { 51 try { 52 return get(key); 53 } catch (ExecutionException e) { 54 throw new UncheckedExecutionException(e.getCause()); 55 } 56 } 57 58 @Override getAll(Iterable<? extends K> keys)59 public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException { 60 Map<K, V> result = Maps.newLinkedHashMap(); 61 for (K key : keys) { 62 if (!result.containsKey(key)) { 63 result.put(key, get(key)); 64 } 65 } 66 return ImmutableMap.copyOf(result); 67 } 68 69 @Override apply(K key)70 public final V apply(K key) { 71 return getUnchecked(key); 72 } 73 74 @Override refresh(K key)75 public void refresh(K key) { 76 throw new UnsupportedOperationException(); 77 } 78 } 79