1 /*
2  * Copyright (C) 2011 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 
15 package com.google.common.cache;
16 
17 import com.google.common.annotations.GwtIncompatible;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.Maps;
20 import com.google.common.util.concurrent.UncheckedExecutionException;
21 import java.util.Map;
22 import java.util.concurrent.Callable;
23 import java.util.concurrent.ExecutionException;
24 
25 /**
26  * This class provides a skeletal implementation of the {@code Cache} interface to minimize the
27  * effort required to implement this interface.
28  *
29  * <p>To implement a cache, the programmer needs only to extend this class and provide an
30  * implementation for the {@link #get(Object)} and {@link #getIfPresent} methods. {@link
31  * #getUnchecked}, {@link #get(Object, Callable)}, and {@link #getAll} are implemented in terms of
32  * {@code get}; {@link #getAllPresent} is implemented in terms of {@code getIfPresent}; {@link
33  * #putAll} is implemented in terms of {@link #put}, {@link #invalidateAll(Iterable)} is implemented
34  * in terms of {@link #invalidate}. The method {@link #cleanUp} is a no-op. All other methods throw
35  * an {@link UnsupportedOperationException}.
36  *
37  * @author Charles Fry
38  * @since 11.0
39  */
40 @GwtIncompatible
41 public abstract class AbstractLoadingCache<K, V> extends AbstractCache<K, V>
42     implements LoadingCache<K, V> {
43 
44   /** Constructor for use by subclasses. */
AbstractLoadingCache()45   protected AbstractLoadingCache() {}
46 
47   @Override
getUnchecked(K key)48   public V getUnchecked(K key) {
49     try {
50       return get(key);
51     } catch (ExecutionException e) {
52       throw new UncheckedExecutionException(e.getCause());
53     }
54   }
55 
56   @Override
getAll(Iterable<? extends K> keys)57   public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException {
58     Map<K, V> result = Maps.newLinkedHashMap();
59     for (K key : keys) {
60       if (!result.containsKey(key)) {
61         result.put(key, get(key));
62       }
63     }
64     return ImmutableMap.copyOf(result);
65   }
66 
67   @Override
apply(K key)68   public final V apply(K key) {
69     return getUnchecked(key);
70   }
71 
72   @Override
refresh(K key)73   public void refresh(K key) {
74     throw new UnsupportedOperationException();
75   }
76 }
77