Debian Codegraph @

sdk-common/src/main/java/com/android/ide/common/caching/CreatingCache.java

raw
1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package com.android.ide.common.caching;
18
19 import static com.google.common.base.Preconditions.checkArgument;
20
21 import com.android.annotations.NonNull;
22 import com.android.annotations.Nullable;
23 import com.android.annotations.VisibleForTesting;
24 import com.android.annotations.concurrency.GuardedBy;
25 import com.google.common.collect.Maps;
26
27 import java.util.Map;
28 import java.util.concurrent.CountDownLatch;
29
30 /**
31 * A cache that handles creating the values when they are not present in the map.
32 *
33 * Calls to {@link #get(Object)} returns the value, calling into {@link ValueFactory} if it
34 * was not created. If the creation takes a long time, other threads can still query the cache
35 * for the same or different keys. Calls for the same key will block until the value has been
36 * created. Calls for different keys will return right away if the key is available.
37 *
38 * This is very similar to Guava's LoadingCache, without the automated clean-up based on size
39 * or time.
40 * This is extracted from the PreDexCache of the Gradle plugin which has different requirements
41 * (reloading cached info from disk)
42 *
43 * This class is thread-safe.
44 *
45 * TODO Move PreDexCache to be based on this.
46 *
47 */
48 public class CreatingCache<K, V> {
49
50 @GuardedBy("this")
51 private final Map<Object, V> mCache = Maps.newHashMap();
52 @GuardedBy("this")
53 private final Map<Object, CountDownLatch> mProcessedValues = Maps.newHashMap();
54
55 @NonNull
56 private final ValueFactory<K, V> mValueFactory;
57
58 /**
59 * A factory creating values based on keys.
60 * @param <K> the type of the key
61 * @param <V> the type of the value
62 */
63 public interface ValueFactory<K, V> {
64
65 /**
66 * Creates a value based on a given key.
67 * @param key the key
68 * @return the value
69 */
70 @NonNull
71 V create(@NonNull K key);
72 }
73
74 public CreatingCache(@NonNull ValueFactory<K, V> valueFactory) {
75 mValueFactory = valueFactory;
76 }
77
78 /**
79 * Queries the cache for a given key. If the value is not present, this blocks until it is.
80 *
81 * If this is the first thread requesting the value, then this trigger creation of the value
82 * through the {@link ValueFactory}.
83 *
84 * @param key the given key.
85 * @return the value, or null if the thread was interrupted while waiting for the value to be created.
86 */
87 @Nullable
88 public V get(@NonNull K key) {
89 return get(key, null);
90 }
91
92 /**
93 * A Query Listener used for testing.
94 *
95 * @see #get(Object, QueryListener)
96 */
97 @VisibleForTesting
98 interface QueryListener {
99 void onQueryState(@NonNull State state);
100 }
101
102 /**
103 * Queries the cache for a given key. If the value is not present, this blocks until it is.
104 *
105 * This version allows for a listener that is notified when the state of the query is known.
106 * This allows knowing the state while the method is blocked waiting for creation of the value
107 * in this thread or another. This is used for testing.
108 *
109 * @param key the given key.
110 * @param queryListener the listener.
111 * @return the value, or null if the thread was interrupted while waiting for the value to be created.
112 *
113 * @see #get(Object)
114 */
115 @VisibleForTesting
116 V get(@NonNull K key, @Nullable QueryListener queryListener) {
117 ValueState<V> state = findValueState(key);
118
119 if (queryListener != null) {
120 queryListener.onQueryState(state.getState());
121 }
122
123 switch (state.getState()) {
124 case EXISTING_VALUE:
125 return state.getValue();
126 case NEW_VALUE:
127 // create the actual value content.
128 V value = mValueFactory.create(key);
129
130 // add to cache, and enable other threads to use the value.
131 addNewValue(key, value, state.getLatch());
132
133 return value;
134 case PROCESSED_VALUE:
135 // wait for value to become available
136 try {
137 state.getLatch().await();
138 } catch (InterruptedException e) {
139 Thread.currentThread().interrupt();
140 return null;
141 }
142 synchronized (this) {
143 // get it from the map cache.
144 return mCache.get(key);
145 }
146 default:
147 throw new IllegalStateException("unsupported ResultType: " + state.getState());
148 }
149 }
150
151 /**
152 * Clears the cache of all values.
153 *
154 * @throws IllegalStateException if values are currently being created.
155 */
156 public synchronized void clear() {
157 if (!mProcessedValues.isEmpty()) {
158 throw new IllegalStateException("Cache values are being processed");
159 }
160
161 mCache.clear();
162 }
163
164 /**
165 * State of values.
166 */
167 @VisibleForTesting
168 enum State { EXISTING_VALUE, NEW_VALUE, PROCESSED_VALUE
169 }
170
171 /**
172 * A Value State. This contains the Type as {@link State}, and a optional value {@link V}
173 * or latch.
174 * @param <V> the value type
175 */
176 private static final class ValueState<V> {
177
178 @NonNull
179 private final State mType;
180 private final V mValue;
181 private final CountDownLatch mLatch;
182
183 ValueState(V value) {
184 this(State.EXISTING_VALUE, value, null);
185 }
186
187 ValueState(@NonNull State type, CountDownLatch latch) {
188 this(type, null, latch);
189 checkArgument(type != State.EXISTING_VALUE);
190 }
191
192 private ValueState(@NonNull State type, V value, CountDownLatch latch) {
193 mType = type;
194 mValue = value;
195 mLatch = latch;
196 }
197
198 @NonNull
199 public State getState() {
200 return mType;
201 }
202
203 @NonNull
204 public V getValue() {
205 return mValue;
206 }
207
208 @NonNull
209 public CountDownLatch getLatch() {
210 return mLatch;
211 }
212 }
213
214 /**
215 * Returns the state of the value for a given key.
216 *
217 * If the value does not exist, prepares a latch to control availability of the value.
218 *
219 * @param key the key
220 * @return a ValueState instance.
221 */
222 @NonNull
223 private synchronized ValueState<V> findValueState(@NonNull K key) {
224 V value = mCache.get(key);
225
226 // value exists, just return the state.
227 if (value != null) {
228 return new ValueState<V>(value);
229 }
230
231 // check if the value is currently being created
232 CountDownLatch latch = mProcessedValues.get(key);
233 if (latch != null) {
234 // return the latch allowing to wait for end of creation.
235 return new ValueState<V>(State.PROCESSED_VALUE, latch);
236 }
237
238 // new value: create a latch to allow others to wait until creation is done.
239 latch = new CountDownLatch(1);
240 mProcessedValues.put(key, latch);
241 return new ValueState<V>(State.NEW_VALUE, latch);
242 }
243
244 /**
245 * Adds a new value to the cache and release threads waiting for it.
246 * @param key the key
247 * @param value the value
248 * @param latch the latch holding the threads.
249 */
250 private synchronized void addNewValue(
251 @NonNull K key,
252 @NonNull V value,
253 @NonNull CountDownLatch latch) {
254 mCache.put(key, value);
255 mProcessedValues.remove(key);
256 latch.countDown();
257 }
258 }