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 com.google.errorprone.annotations.CanIgnoreReturnValue; 022import java.util.Map; 023import java.util.concurrent.Callable; 024import java.util.concurrent.ExecutionException; 025 026/** 027 * This class provides a skeletal implementation of the {@code Cache} interface to minimize the 028 * effort required to implement this interface. 029 * 030 * <p>To implement a cache, the programmer needs only to extend this class and provide an 031 * implementation for the {@link #get(Object)} and {@link #getIfPresent} methods. {@link 032 * #getUnchecked}, {@link #get(Object, Callable)}, and {@link #getAll} are implemented in terms of 033 * {@code get}; {@link #getAllPresent} is implemented in terms of {@code getIfPresent}; {@link 034 * #putAll} is implemented in terms of {@link #put}, {@link #invalidateAll(Iterable)} is implemented 035 * in terms of {@link #invalidate}. The method {@link #cleanUp} is a no-op. All other methods throw 036 * an {@link UnsupportedOperationException}. 037 * 038 * @author Charles Fry 039 * @since 11.0 040 */ 041@GwtIncompatible 042@ElementTypesAreNonnullByDefault 043public abstract class AbstractLoadingCache<K, V> extends AbstractCache<K, V> 044 implements LoadingCache<K, V> { 045 046 /** Constructor for use by subclasses. */ 047 protected AbstractLoadingCache() {} 048 049 @CanIgnoreReturnValue // TODO(b/27479612): consider removing this? 050 @Override 051 public V getUnchecked(K key) { 052 try { 053 return get(key); 054 } catch (ExecutionException e) { 055 throw new UncheckedExecutionException(e.getCause()); 056 } 057 } 058 059 @Override 060 public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException { 061 Map<K, V> result = Maps.newLinkedHashMap(); 062 for (K key : keys) { 063 if (!result.containsKey(key)) { 064 result.put(key, get(key)); 065 } 066 } 067 return ImmutableMap.copyOf(result); 068 } 069 070 @Override 071 public final V apply(K key) { 072 return getUnchecked(key); 073 } 074 075 @Override 076 public void refresh(K key) { 077 throw new UnsupportedOperationException(); 078 } 079}