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 com.google.common.annotations.Beta; 020 import com.google.common.collect.ImmutableMap; 021 import com.google.common.collect.Maps; 022 import com.google.common.util.concurrent.UncheckedExecutionException; 023 024 import java.util.Map; 025 import java.util.concurrent.Callable; 026 import java.util.concurrent.ExecutionException; 027 028 /** 029 * This class provides a skeletal implementation of the {@code Cache} interface to minimize the 030 * effort required to implement this interface. 031 * 032 * <p>To implement a cache, the programmer needs only to extend this class and provide an 033 * implementation for the {@link #get(Object)} and {@link #getIfPresent} methods. 034 * {@link #getUnchecked}, {@link #get(Object, Callable)}, and {@link #getAll} are implemented in 035 * terms of {@code get}; {@link #getAllPresent} is implemented in terms of {@code getIfPresent}; 036 * {@link #putAll} is implemented in terms of {@link #put}, {@link #invalidateAll(Iterable)} is 037 * implemented in terms of {@link #invalidate}. The method {@link #cleanUp} is a no-op. All other 038 * methods throw an {@link UnsupportedOperationException}. 039 * 040 * @author Charles Fry 041 * @since 11.0 042 */ 043 @Beta 044 public abstract class AbstractLoadingCache<K, V> 045 extends AbstractCache<K, V> implements LoadingCache<K, V> { 046 047 /** Constructor for use by subclasses. */ 048 protected AbstractLoadingCache() {} 049 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 }