001/* 002 * Copyright (C) 2011 The Guava Authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 005 * in compliance with the License. You may obtain a copy of the License at 006 * 007 * http://www.apache.org/licenses/LICENSE-2.0 008 * 009 * Unless required by applicable law or agreed to in writing, software distributed under the License 010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 011 * or implied. See the License for the specific language governing permissions and limitations under 012 * the License. 013 */ 014 015package com.google.common.cache; 016 017import com.google.common.annotations.GwtIncompatible; 018import com.google.common.collect.ImmutableMap; 019import com.google.common.collect.Maps; 020import com.google.common.util.concurrent.UncheckedExecutionException; 021import java.util.Map; 022import java.util.concurrent.Callable; 023import java.util.concurrent.ExecutionException; 024 025/** 026 * This class provides a skeletal implementation of the {@code Cache} interface to minimize the 027 * effort required to implement this interface. 028 * 029 * <p>To implement a cache, the programmer needs only to extend this class and provide an 030 * implementation for the {@link #get(Object)} and {@link #getIfPresent} methods. {@link 031 * #getUnchecked}, {@link #get(Object, Callable)}, and {@link #getAll} are implemented in terms of 032 * {@code get}; {@link #getAllPresent} is implemented in terms of {@code getIfPresent}; {@link 033 * #putAll} is implemented in terms of {@link #put}, {@link #invalidateAll(Iterable)} is implemented 034 * in terms of {@link #invalidate}. The method {@link #cleanUp} is a no-op. All other methods throw 035 * an {@link UnsupportedOperationException}. 036 * 037 * @author Charles Fry 038 * @since 11.0 039 */ 040@GwtIncompatible 041@ElementTypesAreNonnullByDefault 042public abstract class AbstractLoadingCache<K, V> extends AbstractCache<K, V> 043 implements LoadingCache<K, V> { 044 045 /** Constructor for use by subclasses. */ 046 protected AbstractLoadingCache() {} 047 048 @Override 049 public V getUnchecked(K key) { 050 try { 051 return get(key); 052 } catch (ExecutionException e) { 053 throw new UncheckedExecutionException(e.getCause()); 054 } 055 } 056 057 @Override 058 public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException { 059 Map<K, V> result = Maps.newLinkedHashMap(); 060 for (K key : keys) { 061 if (!result.containsKey(key)) { 062 result.put(key, get(key)); 063 } 064 } 065 return ImmutableMap.copyOf(result); 066 } 067 068 @Override 069 public final V apply(K key) { 070 return getUnchecked(key); 071 } 072 073 @Override 074 public void refresh(K key) { 075 throw new UnsupportedOperationException(); 076 } 077}