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 com.google.common.annotations.GwtIncompatible; 18 import com.google.common.collect.ImmutableMap; 19 import com.google.common.collect.Maps; 20 import com.google.common.util.concurrent.UncheckedExecutionException; 21 import java.util.Map; 22 import java.util.concurrent.Callable; 23 import java.util.concurrent.ExecutionException; 24 25 /** 26 * This class provides a skeletal implementation of the {@code Cache} interface to minimize the 27 * effort required to implement this interface. 28 * 29 * <p>To implement a cache, the programmer needs only to extend this class and provide an 30 * implementation for the {@link #get(Object)} and {@link #getIfPresent} methods. {@link 31 * #getUnchecked}, {@link #get(Object, Callable)}, and {@link #getAll} are implemented in terms of 32 * {@code get}; {@link #getAllPresent} is implemented in terms of {@code getIfPresent}; {@link 33 * #putAll} is implemented in terms of {@link #put}, {@link #invalidateAll(Iterable)} is implemented 34 * in terms of {@link #invalidate}. The method {@link #cleanUp} is a no-op. All other methods throw 35 * an {@link UnsupportedOperationException}. 36 * 37 * @author Charles Fry 38 * @since 11.0 39 */ 40 @GwtIncompatible 41 @ElementTypesAreNonnullByDefault 42 public abstract class AbstractLoadingCache<K, V> extends AbstractCache<K, V> 43 implements LoadingCache<K, V> { 44 45 /** Constructor for use by subclasses. */ AbstractLoadingCache()46 protected AbstractLoadingCache() {} 47 48 @Override getUnchecked(K key)49 public V getUnchecked(K key) { 50 try { 51 return get(key); 52 } catch (ExecutionException e) { 53 throw new UncheckedExecutionException(e.getCause()); 54 } 55 } 56 57 @Override getAll(Iterable<? extends K> keys)58 public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException { 59 Map<K, V> result = Maps.newLinkedHashMap(); 60 for (K key : keys) { 61 if (!result.containsKey(key)) { 62 result.put(key, get(key)); 63 } 64 } 65 return ImmutableMap.copyOf(result); 66 } 67 68 @Override apply(K key)69 public final V apply(K key) { 70 return getUnchecked(key); 71 } 72 73 @Override refresh(K key)74 public void refresh(K key) { 75 throw new UnsupportedOperationException(); 76 } 77 } 78