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
041public abstract class AbstractLoadingCache<K, V> extends AbstractCache<K, V>
042    implements LoadingCache<K, V> {
043
044  /** Constructor for use by subclasses. */
045  protected AbstractLoadingCache() {}
046
047  @Override
048  public V getUnchecked(K key) {
049    try {
050      return get(key);
051    } catch (ExecutionException e) {
052      throw new UncheckedExecutionException(e.getCause());
053    }
054  }
055
056  @Override
057  public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
058    Map<K, V> result = Maps.newLinkedHashMap();
059    for (K key : keys) {
060      if (!result.containsKey(key)) {
061        result.put(key, get(key));
062      }
063    }
064    return ImmutableMap.copyOf(result);
065  }
066
067  @Override
068  public final V apply(K key) {
069    return getUnchecked(key);
070  }
071
072  @Override
073  public void refresh(K key) {
074    throw new UnsupportedOperationException();
075  }
076}