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